PYTHON BASICS
Python Basics: Functions
We’ve been taking a look at control structures over the last few articles, seeing how they enable us to control how our program executes in different scenarios. Particularly, we looked at the if-statement for branching, and the while-statement for executing the same action multiple times.
It is also possible to compose these control structures to create more complex programs.
However, this can quickly get messy as you can see. It is difficult to understand what programs like these do at a glance when different responsibilities are mixed together.
In this article, we’ll learn how to clean up our code using functions. Particularly, we’ll learn what functions are, and the benefits of using them.
Defining a function
Functions in programming are similar to functions in mathematics. A mathematical function function, f(x) = 3x + 2, for example, allows us to specify some value x. The function, f, does something with the input x, and gives us a result back.
A programming function in Python does something similar, with more capabilities. For example, the same f(x) = 3x + 2 function can be written in Python as:
The def keyword tells Python that we are about to define a function called f. The x within the parentheses means that this function f expects to receive one value as input.
In Calling a Function, we’ll see that this x parameter behaves as a variable that holds the value that we input into the function.
The rest of the indented lines is the Python code that will be executed when we eventually get to calling the function.
At this point, none of that indented code is executed: we’re only telling Python that “this is the code to be executed when I call the function f”.
The last line with the return keyword tells Python that the output of calling this function should be the result of m * x + b, which is 3 * x + 2 for whatever x ends up being.
Calling a function
Now that we have defined a function, we can now start to use it in the rest of our code. We call functions in Python the same way we do in math:
This code will execute the function f using 1 as the value for the parameter x. This means that f will run as if x=1, so the result of the function will be 3*1+2 which evaluates to 5.
Calling the function evaluates to its result which means that we can assign the result to a variable as follows:
Now the y variable contains the result of f(1), which is 5.
We can keep calling f with any input for x without having to write 3*x + 2 ever again.
Beyond Math
Functions in Python have more capabilities that using them to define math formulas. For example, you can define your Python function to:
- Execute virtually any Python code
- Use multiple input parameters
- Return any type of value — not just numbers
- Return nothing at all
1 . Execute any code
One of the benefits of functions in programming is they allow you to define any piece of code that you want to reuse over and over again. You are not limited to math expressions. For example, I can define a function that does the Fizz Buzz game from last article up to any number x.
Recall from last article that the Fizz Buzz code will go from 1 up to any number of we specify, and do the following:
- output “Fizz” if the current number is divisible by 3
- “Buzz” if divisible by 5
- “FizzBuzz” if divisible by 5 and 3
- or just output the current number otherwise
Notice how the maximum number limit is the variable x. This gives us the flexibility to call fizzbuzz with any number we give it as the limit. And we can call the function as many times as we want without having the write the code again.
2. Use multiple input parameters
Python functions also allow you to specify more than one parameters for your function. This is useful when a function needs multiple values to work. A simple example is defining a add function that adds two numbers together.
Now we can add two numbers in the following way by specifying the input values — i.e., arguments:
3. Return any data type
With functions in Python, you are not restricted to just returning a number. Your function can return any data type you want. For example, you can define the following function that returns True if a number is divisible by another number, and otherwise False.
We can then use it to check for divisibility:
Note the two return statements in the divisible function. The return keyword is not required to be the last line of the function. You can have as many return keywords as you want, however, once the Python execution of a function reaches a return keyword, it will stop running the function and immediately return the specified value back.
Get Gideon Oludeyi’s stories in your inbox
Join Medium for free to get updates from this writer.
This means that the following myfunction function will not run any code after the first return statement.
Now we can use the divisible function to simplify our fizzbuzz function in the following way:
4. Return nothing
In addition, you can also choose to not return any value from your Python function. We already did this with the fizzbuzz function above. We never specified a return statement so the function returns nothing. To be precise, when a function does not explicitly have a return statement, it implicitly returns a special value in Python called None, which represents the idea of “no value”.
When you call fizzbuzz, the numbers will be displayed on the console, but that is just the effect of print, and is not the return value of the function.
Now when you try to print the result variable, you get the special None value which means that the fizzbuzz returned None implicitly.
Of course, you can also be explicit about it as well.
Fun Fact
print is a function that displays its input values as text on the console, but it also returns None.
The first output line is the effect of printing the number 5, but the second output line is value that the first print call returned, which is None.
There are many more features of Python functions beyond what was covered here, such as variable argument lists, keyword arguments, generators, and methods, but those are more advanced concepts beyond the scope of this introductory article.
Built-in Functions
There are a special set of functions that are made available in every Python program. These functions are called built-in functions because they are built into Python and you do not have to define them yourself because Python already defines them for you. The list of built-in functions is available at Built-in Functions — docs.python.org.
One such function is the print function which we have always been using. This function accepts any number of arguments and displays them as text to the Python console.
Another built-in function is the input function which accepts a single string value, displays it to the Python console, and returns the text that the user types into the console as a string.
Simplifying Code
Lastly, let’s apply what we know about functions to clean up the original example program at the start.
- This program starts with a while-statement that increments the number value one-by-one from 1 to 10.
- In each iteration of the loop, the if-statement checks whether the current number value is an even number.
- If the number is even, the inner loop calculates the sum of all the numbers starting from 0 to whatever number is and displays it on the screen.
- Otherwise if the number of odd, the inner loop calculates the product of all the numbers starting from 1 to whatever `number` is and displays it on the screen.
On a simpler level, the program displays the sum of all numbers up to each even number less than 10, and the product of all number up to each odd number less than 10.
Let’s start by extracting [3.] into a function. That is, the code that calculates the sum of all numbers from 0 to some number. Since we are depending on a number variable that we don’t know exactly what the value will be, we can turn it into a parameter for the function.
Now the original code looks a bit simpler to ready.
Let’s do the same for [4.], the code for multiplying the odd numbers.
Now if you look only at the original code, and ignore the total and product function definitions, it’s clearer what this program is doing.
One benefit to using functions is that it improves readability. You don’t have to keep track of every single thing that is going on in the program — you focus on understanding one function in isolation.
Lastly, we can extract [2.], where we check whether the number is even.
Although the is_even function is a very small change, it goes a long way in simplifying the program. I don’t have to try to understand what number % 2 == 0. I only have to look at the name is_even to understand that the program is doing something different when the number is even.
The simplicity you get from the code is one of the reasons I love using functions.
Conclusion
In this article, we learned at what functions are, how to define them, how to call them, including some of the nuances of using them. We also saw how to use functions to simplify our code to make it easier to understand. So when you are writing a program that is difficult to read or understand, try extracting some of the parts into functions and what it simplify itself in the process.
This marks the end of this PYTHON BASICS series.
There is vastly more to be learned about Python, and programming in general. But I hope this series served as a good introduction to the Python programming language.
Thank you for being a part of the community
Before you go:
- Be sure to clap and follow the writer ️👏️️
- Follow us: X | LinkedIn | YouTube | Newsletter | Podcast | Differ | Twitch
- Check out CoFeed, the smart way to stay up-to-date with the latest in tech 🧪
- Start your own free AI-powered blog on Differ 🚀
- Join our content creators community on Discord 🧑🏻💻
- For more content, visit plainenglish.io + stackademic.com








