If you want to reuse code, you can use a function.

This prevents you from writing the same thing over and over again.

A function has a unique distinct name in the program. Once you call a function it will execute one or more lines of codes, which we will call a code block.

Related Course: Complete Python Programming Course & Exercises

What are Functions?

A function is code. You can use functions to divide your program in “blocks of code”. This makes your code more readable and your life easier. You have likely already used one or more functions, such as the print function:

print("Hello world")

A function can be called more than once:

print("Coffee")
print("Tea")
print("Sugar")

Python Function

The syntax for making a Python function is:

def <function_name>([<parameters>]):
<statement(s)

The meaning is:

  • def tells Python you want to create a function

  • function_name is the identifier, it must be unique

  • parameters optional list of parameters that can be passed in the function

  • : end of function header

  • <statement(s) lines of code. This is called the function body. It must have four space indention.

It’s possible to create both simple and complex functions.
Start with a small example, we define a function f() and call it:

def f():
print('function body')

# Call function
f()

A function can be called as many times as you want, so this is possible:

f()
f()
f()

A function body can have many lines of code:

def hello():
print("Dear Java")
print("Hows that JRE coming along?")
print("Your sincerly,")
print("Python")

hello()

python function

If you are a Python beginner, then I highly recommend this book.

Function parameters

Functions can take arguments. They are positional, the order should remain the same.

The example below takes a single argument:

def hello(name):
print("Good'day " + name)

hello("Alice")

To take multiple arguments, add a comma between each of them.

def f(name,salary):
print(f"{name} has ${salary}")

Then you can call it like this:

f("Alice",80000)

The function parameters in the function call must remain in the same order as the definition.
If you have this function:

def f(a,b,c):
pass

Then you must call the function as f(a,b,c) not f(a,c,b) or f(c,b,a).
They must be the same number of parameters. So not f(a,b) or f(a,b,c,d).

The pass statement is an empty function body.

Default parameters

You can set a default parameter. This is set when you don’t define any argument.

>>> f(6)
6
>>> f(7)
7
>>> # prints default value
>>> f()
5

If you have multiple parameters, the same idea is true:

>>> def f(x=5,y=4):
... print(f"{x} {y}")
...
>>> f()
5 4
>>> f(3)
3 4
>>> f(10,10)
10 10
>>>

Function scope

Variables you create in the function body only exist within it.

If you create a function with a variable inside it:

>>> def f():
... x = 5

Then that variable can only be accessed within the function body.

If you try to access it outside the function body, it will throw an error:

>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>

So function variables live inside the function body.

If you want to use the function variable in your program, you must use return.

Return value

It is also possible to store the output of a function in a variable. To do so, we use the keyword return.

The function sum(a,b) returns the output.

>>> def sum(a,b):
... x = a + b
... return x
...
>>> cost = sum(100,60)
>>> print(cost)
160
>>>

Without the return statement, variable x would only exist within the function body. The variable name need not be the same, in this case we store the output as variable cost.

python function return variable

A function can return more than one variable:

>>> def f(a,b,c):
... return a,b,c
...
>>> x,y,z = f(1,2,3)
>>> x
1
>>> y
2
>>> z
3
>>>

Variable-Length Argument Lists

By default, Python functions take a fixed number of arguments. That is fine for most functions, but sometimes you want the number of arguments to be of variable length.

# takes 2 arguments
def f(a,b):

# takes 3 arguments
def f(a,b,c):

# takes 4 arguments
def f(a,b,c,d):

So you must call the function with the same number of arguments.
What if you want a variable-length?

Then you can use a list:

>>> def f(x):
... for item in x:
... print(item)

This gives you the freedom to call it with any “number of parameters”:

>>> f([1])
>>> f([1,2])
>>> f([1,2,3])
>>> f([1,2,3,4])
>>> f([1,2,3,4,5])

Docstring

You can add documentation to your function. The first string after the function header is the documentation string. You can output it with the __doc__ attribute.

This way you can request what a function does:

>>> print(print.__doc__)
...
>>> print(dir.__doc__)

If you want to create your own docstring you can do this:

>>> def hello():
... """This function prints hello world"""
... print("hello world")
...

Then output it like this:

>>> print(hello.__doc__)
This function prints hello world
>>>

A docstring is optional.

Documentating code is a good practice in general. If you have large complex programs, you should add documentation at all time.

The main() function

In some Python scripts, a main function is defined. Something like this:

def main():
print("Hello World!")

if __name__ == "__main__":
main()

The main function is optional, your programs will run without it.

The program starts in the main() function. This is common in other programming languages (C, C++).

The line if __name__ == "__main__": is True if the program starts, so main() is called.

This main function is common in Python files that are executed as a script and imported in another module.

Conclusion

In this tutorial you learned:

  • What Python functions are
  • How to define Python functions
  • Calling Python functions
  • All about function arguments

If you are a Python beginner, then I highly recommend this book.

Download exercises