The function is a crucial concept in the world of programming. In this article, weβll explore Python functions. Youβll learn why they are so important, how to define functions with Pythonβs def keyword, how to call functions, and weβll learn about a topic that arises when using functions: variable scope.
Table of Contents
What is a function in Python?
Letβs define what a function is, exactly:
- Function
- A Python function is a named section of a program that performs a specific task and, optionally, returns a value
Functions are the real building blocks of any programming language. We define a Python function with the def
keyword. But before we start doing so, letβs first go over the advantages of functions, and letβs look at some built-in functions that you might already know.
Advantages of using functions
Code reuse
A Python function can be defined once and used many times. So it aids in code reuse: you donβt want to write the same code more than once.
Functions are a great way to keep your code short, concise, and readable. By giving a function a well-chosen name, your code will become even more readable because the function name directly explains what will happen. This way, others (or future you) can read your code, and without looking at all of it, understand what itβs doing anyway because of the well-chosen function names.
Other forms of code reuse are explained later on. E.g., you can also group code into modules and packages.
Parameters
Functions accept a parameter, and youβll see how this works in a moment. The big advantage here, is that you can alter the functionβs behavior by changing the parameter.
Return values
A function can return a value. This value is often the result of some calculation or operation. In fact, a Python function can even return multiple values.
Built-in Python functions
Before we start defining functions ourselves, weβll look at some of Pythonβs built-in functions. Letβs start with the most well-known built-in function, called print
:
>>> print('Hello, readers!')
Hello, readers!
>>> print(15)
15
Code language: Python (python)
Print takes an argument and prints it to the screen.
As stated in our definition, functions can optionally return a value. However, print
does not return anything. Because it prints something to the screen, it might look like it does, but it doesnβt. We can check this by assigning the result of a print statement to a Python variable:
>>> result = print('Hello')
Hello
>>> print(result)
None
Code language: Python (python)
None
is a special type of value in Python, basically meaning βnothing.β
Another built-in function that does return a value is len()
. It returns the length of whatever you feed it:
>>> mylength = len('Hello')
>>> print(mylength)
5
Code language: Python (python)
Creating a Python function
Now that we know how to use a function, letβs create a simple one ourselves. To do so, we use Pythonβs def
keyword:
>>> def say_hi():
... print('Hi!')
...
>>> say_hi()
Hi!
Code language: Python (python)
Itβs just a few lines, but a lot is going on. Letβs dissect this:
- First, we see the keyword
def
, which is Pythonβs keyword to define a function. - Next comes our function name, say_hi.
- Then we encounter two parentheses, (), which indicate that this function does not accept any parameters (unlike
print
andlen
). - We end the line with a colon (:)
- And finally, we bump into a feature that sets Python apart from many other programming languages: indentation.
Indentation
Python uses indentation to distinguish blocks of code that belong together. Consecutive lines with equal indentation are part of the same block of code.
To tell Python that the following lines are the body of our function, we need to indent them. You indent lines with the TAB key on your keyboard. In Python, itβs good style to use four spaces for indentation. The entire Python community does so. If you hit the TAB key, the Python interactive shell (REPL) and all decent editors will automatically indent with four spaces.
Back to our function: it has only one line of code in its body: the print command. After it, we hit enter one extra time to let the Python REPL know that this is the end of the function. This is important. A function must always be followed by an empty line to signal the end of the function. Finally, we can call our function with say_hi()
.
Python function parameters and arguments
We can make this more interesting by allowing an argument to be passed to our function. Again we define a function with def, but we add a variable name between the parentheses:
>>> def say_hi(name):
... print('Hi', name)
...
>>> say_hi('Erik')
Hi Erik
Code language: Python (python)
Our function now accepts a value, which gets assigned to the variable name. We call such variables the parameter, while the actual value we provide (βErikβ) is called the argument.
- Parameters and arguments
- A Python function can have parameters. The values we pass through these parameters are called arguments.
As you can see, print()
accepts multiple arguments, separated by a comma. This allows us to print both βhiβ and the provided name. For our convenience, print()
automatically puts a space between the two strings.
Python function with multiple arguments
Letβs make this even wilder and define a function with multiple arguments:
>>> def welcome(name, location):
... print("Hi", name, "welcome to", location)
...
>>> welcome('Erik', 'this tutorial')
Hi Erik welcome to this tutorial
Code language: Python (python)
Itβs not that hard; you just add more arguments to the function definition, separated by commas.
Returning from a function
A function runs until the end of that function, after which Python returns to where the function was called from. In the following example, I want you to predict the output before you run it:
Did your expectations match with reality? If so, you have a good understanding of how a function call works. Some people at this point expect to see the text βLetβs greet the entire worldβ twice. If you are one of them, donβt worry and keep reading.
Python keeps track of the point where the function is called. In our case, itβs at line 5. Once called, Python runs the code block inside the function line by line until it reaches the end of that function. Once the end of the function is reached, Python jumps back to where the function was called from and continues with the following line! In this case, there is no following line, so the program ends.
In short, a function call is not a jump or βgo toβ but a call to a piece of reusable code that returns to where it was called from. A function call is also an expression: most functions return a value.
Returning values
So far, our function only printed something and returned nothing. What makes functions a lot more usable is the ability to return a value. Letβs see an example of how a Python function can return a value:
As you can see, we use the keyword return
to return a value from our function. Functions that return a value can be used everywhere we can use an expression. In the above example, we can assign the returned value to the variable result
.
We could have used the function in an if statement as well. For example:
if add(1, 1) == 2:
print("That's what you'd expect!")
Code language: Python (python)
Empty return statement
If your function does not return anything, but you still want to return from the function, you can use an empty return statement. Hereβs a silly example that uses the startswith()
method of a string. This method checks if the string starts with the given string:
def optional_greeter(name):
if name.startswith('X'):
# We don't greet people with weird names :p
return
print('Hi there, ', name)
optional_greeter('Xander')
Code language: Python (python)
This is an interesting pattern; I call it returning early. Iβd like to return early because the alternative is using blocks of ifβ¦ else statements:
def optional_greeter(name):
if name.startswith('X'):
# We don't greet people with weird names :p
pass
else:
print('Hi there, ', name)
optional_greeter('Xander')
Code language: Python (python)
Which one do you feel looks cleaner? Iβd say the first because it requires less indented code. And although the difference is small with such a small example, this starts to add up when you have bigger chunks of code.
Variable scope
The variable name
only exists inside our function. We say that the variableβs scope name
is limited to the function say_hi
, meaning it doesnβt exist outside of it.
- Scope
- The visibility of a variable is called scope. The scope defines which parts of your program can see and use a variable.
If we define a variable at the so-called top level of a program, it is visible in all places.
Letβs demonstrate this:
>>> def say_hi():
... print("Hi", name)
... answer = "Hi"
...
>>> name = 'Erik'
>>> say_hi()
Hi Erik
>>> print(answer)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'answer' is not defined</module></stdin>
Code language: Python (python)
say_hi
was able to use the variable name
, as expected, because itβs a top-level variable: it is visible everywhere. However, answer
, defined inside say_hi, is not known outside of the function and causes a NameError
. Python gives us an informative and detailed error: βname βanswerβ is not defined.β
Default values and named parameters
A compelling Python feature is the ability to provide default values for the parameters:
>>> def welcome(name='learner', location='this tutorial'):
... print("Hi", name, "welcome to", location)
...
>>> welcome()
Hi learner welcome to this tutorial
>>> welcome(name='John')
Hi John welcome to this tutorial
>>> welcome(location='this epic tutorial')
Hi learner welcome to this epic tutorial
>>> welcome(name='John', location='this epic tutorial')
Hi John welcome to this epic tutorial
Code language: Python (python)
Or, if you prefer, use the interactive example below:
Because our parameters have a default value, you donβt have to fill them in. If you donβt, the default is used. If you do, you override the default with your own value.
Calling Python functions while explicitly naming the parameters differs from what we did up until now. These parameters are called named parameters because we specify both the name and the value instead of just the value. Thanks to these named parameters, the order in which we supply them doesnβt matter. If you think about it, itβs the natural and only way to make default values useful.
If you donβt want to use named parameters, you can. When you rely on position instead of names, you provide what we call positional parameters. The position matters, as can be seen below:
>>> def welcome(name='learner', location='this tutorial'):
... print("Hi", name, "welcome to", location)
...
>>> welcome('Erik', 'your home')
Hi Erik welcome to your home
Code language: Python (python)
For now, youβve learned enough about functions to continue with the tutorial. If you like to learn more, read my Python functions deep dive.