A function is a named block of code you can run again and again. Functions keep programs tidy and avoid repeating yourself.
Defining a function
Use the def keyword, a name, round brackets, and a colon. The body is indented:
def greet():
print('Hello!')
greet() # calls the function
Defining a function does not run it; you must call it with its name and brackets.
Parameters and arguments
A parameter is a placeholder in the definition; an argument is the real value you pass in:
def greet(name):
print('Hi', name)
greet('Sara') # Hi Sara
Returning a value
Use return to send a result back to the caller. That result can be stored in a variable:
def add(a, b):
return a + b
total = add(2, 3) # total is 5
A function without a return statement gives back None.
Default values
A parameter can have a default used when no argument is given:
def greet(name='friend'):
print('Hi', name)
greet() # Hi friend
greet('Ali') # Hi Ali
Several parameters
A function can take more than one parameter. The arguments line up in the same order:
def area(width, height):
return width * height
print(area(4, 5)) # 20
Using the returned value
Because return hands a value back, you can use a function inside a larger expression:
def double(n):
return n * 2
print(double(3) + double(4)) # 14
Local variables
Variables created inside a function live only there. They cannot be seen from outside, which keeps functions self-contained:
def make():
message = 'hi'
return message
print(make()) # hi
Trying to use message outside the function would cause an error. This separation is a good thing: each function manages its own work.
Docstrings and good names
Give a function a clear name that says what it does, such as calculate_total. You may also add a short description in quotes on the first line, called a docstring, to remind readers of its purpose:
def square(n):
'Return n multiplied by itself'
return n * n
Well-named functions with a single job make a program much easier to read and fix later.
Remember
- def defines a function; brackets after its name call it.
- return sends a value back; print only shows it on screen.
- A function with no return gives back None.