In Python, def defines a function: write def, a name, a parenthesized list of parameters and a colon, then indent the body on the following lines. The code in the body does not run until you call the function by name.
def greet(name):
print("Hello, " + name)
greet("Ada")
Example output:
Hello, Ada
The first two lines define greet. The last line calls it, and only then does the print run.
def syntax, line by line
The Python tutorial describes the form this way: the keyword def introduces a function definition, it must be followed by the function name and the parenthesized list of formal parameters, and the statements that form the body start at the next line and must be indented. Here is a definition with each part labelled:
def area(width, height): # def, name, parameters, colon
return width * height # body, indented
defis the keyword. It is lowercase and always the first word of the statement.areais the function name. Use lowercase words joined by underscores, such ascalculate_total, which is the common Python convention.(width, height)are the parameters, the names the function uses for its inputs. The parentheses are required even when there are none:def greet():.- The colon ends the header line. Forgetting it gives a
SyntaxError. - The indented block is the body. All lines of the body must be indented consistently, and a missing indent raises an
IndentationError, covered in the IndentationError guide.
def only defines the function, it does not run it
The language reference says a function definition is an executable statement. Running it binds the function name in the current namespace to a function object. It also says the definition does not execute the function body; that happens only when the function is called. So this program prints nothing:
def say_hi():
print("hi")
To see the output you need the call say_hi(). Writing just say_hi without parentheses refers to the function object and does not run it. Calling is covered in how to call a function in Python and JavaScript.
Because def is a statement that runs, a function must be defined before the line that calls it executes. Calling say_hi() above the def raises a NameError, since the name does not exist yet.
Parameters and arguments
Parameters are the names in the definition. Arguments are the values you pass in the call. With def area(width, height), the call area(3, 4) sets width to 3 and height to 4.
def area(width, height):
return width * height
print(area(3, 4))
print(area(height=5, width=2))
Example output:
12
10
The second call uses keyword arguments, written name=value. The tutorial says keyword arguments must follow positional arguments, their order does not matter, and no argument may receive a value more than once. Breaking that last rule gives an error such as TypeError: function() got multiple values for argument 'a', which is the message the tutorial shows for function(0, a=0). Passing too many positional arguments gives a message of the form combined_example() takes 2 positional arguments but 3 were given.
Default values for parameters
Give a parameter a default with =, and callers can leave it out. The tutorial says this creates a function that can be called with fewer arguments than it is defined to allow.
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(2, 10))
Example output:
25
1024
Parameters with defaults go after the ones without. def power(exponent=2, base) is a syntax error.
The mutable default argument trap
The reference says default parameter values are evaluated from left to right when the function definition is executed: once, when the function is defined, and the same value is used for each call. The tutorial calls this an important warning for mutable defaults such as a list or dictionary. Its own example:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
Example output:
[1]
[1, 2]
[1, 2, 3]
Every call that omits L shares one list, so it keeps growing. The fix from the tutorial is to default to None and build the list inside the function:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
Now each call without L starts with a fresh empty list.
Returning a value from a function
Use return to hand a result back to the caller. The tutorial notes that even a function without a return statement returns a value, None, and that a bare return and falling off the end of the function do the same. So greet("Ada") above evaluates to None after printing. If you assigned its result to a variable, the variable would hold None. The details, including returning several values as a tuple, are in what return does in Python.
Docstrings: documenting a function
The first statement of the body can be a string literal, and Python treats it as the function's documentation string. The reference says it becomes the function's __doc__ attribute. The tutorial says it is good practice to include docstrings in code you write.
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area.__doc__)
help(area)
Example output of the print line:
Return the area of a rectangle.
help(area) prints the signature together with the docstring. Editors also show the docstring when you hover over a call.
Variables inside a function are local
The tutorial explains that running a function creates a new symbol table for its local variables. Assignments inside the function store values there. Reading a name looks in the local table first, then in enclosing functions, then in the global table, then in the built-in names. As a result, a function can read a global variable but cannot reassign it unless the name is declared with a global statement.
count = 10
def show():
count = 99
print(count)
show()
print(count)
Example output:
99
10
The assignment inside show created a separate local count. The global one is unchanged.
Type hints are optional
You can annotate parameters and the return value: def area(width: float, height: float) -> float:. The reference states that the presence of annotations does not change the semantics of a function, so Python does not enforce them when the function runs. Tools such as type checkers and editors read them.
Common mistakes with def
- Missing colon. The header line must end with
:. - Body not indented. At least one indented statement must follow the header. Use
passas a placeholder body if you are not ready to write it. - Defining but never calling. Nothing happens until you write
name(). - Printing instead of returning. A function that only prints gives the caller
None, so it cannot be used in further calculations. - Using a name before the def runs. The call must come after the definition has executed.
- Mutable default arguments. Use
Noneand create the list or dictionary inside.
Frequently asked questions
- What does def stand for in Python?
- def is short for definition. The Python tutorial says the keyword def introduces a function definition, which must be followed by the function name and a parenthesized list of parameters. The body starts on the next line and must be indented.
- Does def run the function?
- No. The language reference says a function definition does not execute the function body; the body runs only when the function is called. Executing def just creates a function object and binds it to the name.
- Can a Python function have no parameters?
- Yes. Write empty parentheses, as in def greet():, and call it the same way: greet(). The parentheses are required in both the definition and the call.
- Why does my list default argument keep growing between calls?
- Default values are evaluated once, when the def statement runs, so every call that omits the argument shares the same list object. Use None as the default and create the list inside the function body, as the Python tutorial recommends.
- Do I need a return statement in every function?
- No. A function without return gives back None, and so does a bare return. Add return only when the caller needs a value from the function.