Functions are reusable pieces of programs. They allow you to give a name to a block of statements, then you can run that block using the specified name anywhere in your program and any number of times.
>> print('Hello, world!') None >> input("Enter your name: ") None >> int("42") 42 >> randint(1, 10) 7
def
def say_hello(): print('Hello, world!')
You can provide arguments to a function, which act as inputs.
def print_max(a, b): if a > b: print(a, 'is maximum') else: print(b, 'is maximum')
Call the function with arguments:
print_max(3, 4)
return
The return statement is used to return a value from a function.
def maximum(x, y): if x > y: return x else: return y
Call the function
print(maximum(2, 3))
Go back to your Calculator program from the beginning of class and refactor it to use functions.
The function arguments should be the two numbers and the operation to perform.
print_max(b=3, a=4)
def say(message, times=1): print(message * times) say('Hello') # => 'Hello' say('World', 5) # => 'WorldWorldWorldWorldWorld'
Variables defined within a function are local to that function.
def func(x): print('x is', x) x = 2 print('Changed local x to', x)
Call the function:
x = 50 func(x) print('x is still', x)
A function can call itself. This is known as recursion.
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1)
You can add documentation to functions using docstrings.
def print_max(a, b): """ Prints the maximum of two numbers. """ a = int(a) # Convert to integers, if possible b = int(b) if a > b: print(a, 'is maximum') else: print(b, 'is maximum')
>>> print(print_max.__doc__) Prints the maximum of two numbers. >>> help(print_max) print_max(a, b) Prints the maximum of two numbers.
These are unecessary but nice to have, especially in Google Colab.
def print_max(a: int, b: int): '''Prints the maximum of two numbers.''' if a > b: print(a, 'is maximum') else: print(b, 'is maximum') print_max(3, "4") # Incorrect type!!!
TODO: This exercise was hard to implement in class. Come up with something better next time.
TODO: We should just skip this
TODO: This was WAAAAY too hard for a first assignment. Should have started with is_prime or literally anything else.