Functions in Python featured image

Defining Functions in Python 3: A Tutorial

In programming, a function is described as a block of instructions that can perform a certain action. A function is generally re-usable. Using functions makes the code more modular. It also opens up the opportunity of re-using the code over and over again in the future.

Python is a robust programming language that supports functions. It already comes with a handful of built-in functions, for example:

  • print(): Prints an object to the terminal.
  • int(): Converts other data types (string or numbers) into an integer.
  • len(): Returns the length of an object.

In this guide, we will showcase defining your own functions and using them in your Python project.

Prerequisites

To perform the steps demonstrated in this guide, you will need the following components ready to go:

Step 1 – Creating a Python Script

First, create a Python script. We will use this script to run and demonstrate our Python codes:

Functions in Python code screenshot 1

Step 2 – Working with Function in Python

  • Defining a Python Function

What is a programming tutorial without the classic “Hello, World” program? Enter the following code in the Python script:

Functions in Python code screenshot 2

Next, run the script using the Python interpreter:

Functions in Python code screenshot 3

So, what is happening here?

  • We’ve defined a function hello() that contains the code to print a string on the screen. You can learn more about indexing and slicing strings in Python here.
  • A function doesn’t run by itself. We have to call it to do its job. We called the hello() function later in the script to do its actions.

This is the key structure any function in Python will follow. Now, we will move to a bit more complex function. Have a look at the following code:

Functions in Python code screenshot 4

Run the script:

Functions in Python code screenshot 5

Here, the function names() asks for a string input. The input is stored in the variable name. The next task is to check if the name contains a vowel. Based on the decision, a string is printed on the screen. Finally, the function it’s called to do its job. Next, we will explore functions with parameters.

  • Function Parameters
    • Basic Parameter Usage

So far, we worked with functions with empty parameters, meaning they don’t require any additional arguments to work. However, we can use function parameters for more versatile and complex functions. In this section, we will have a look at working with function parameters. Have a look at the following code:

Functions in Python code screenshot 6

Then, run the script:

So, what is happening here?

  • The function add_numbers() takes three integers as arguments (located within the function’s parentheses), stored in variables p, q, and r.

  • Some additional calculations are performed. The results are stored in the variables a, b, and c.

  • The result of the calculations is printed on the screen.

  • Finally, the function is called with additional arguments (2, 4, and 6). It prints the result of the calculations on the screen (6, 8, 10).

We will look at another example of using function parameters. This time, the parameters will handle string values. You can use string formatters for more versatile strings. Have a look at the following code:

Functions in Python code screenshot 7

After that, run the Python script:

Here:

  • The function profile_info() takes two parameters: username (string) and followers (integer).

  • It prints that info on the screen using the print() function.

  • In the first call of profile_info() function, we are providing the function arguments similar to the original function definition ( username and followers, respectively).

  • In the second call of profile_info(), however, we are not providing the arguments in sequence. Here, you have to specify the keywords and assign their values.

The next code is another example of providing function arguments in a different order. Have a look at the code:

Functions in Python code screenshot 8

Run the script:

Here:

  • In the profile_info() function call, we are providing argument values by their keywords. This allows us to assign value in whatever sequence we see fit.

However, it’s recommended to provide arguments in sequence to the original function definition.

  • Default Parameter Value

In Python, we can also set a default value for the parameter. This allows calling the function without providing value for the particular argument. The function will assume the default value and operate based on that.

To demonstrate this concept, jump right into the editor and type the following code:

Functions in Python code screenshot 9

Run the code using the Python interpreter:

So, what happened here?

  • Notice that in the definition of the function profile_info(), we set “ followers=100”. This sets the default value of the argument followers to 100.
  • In the first call of the function profile_info(), we only provided value for the parameter username but not for followers. As the output shows, it’s using the default value 100.
  • In the second call of the function profile_info(), we provided values for both of the parameters. In that case, the function utilized the values provided for followers, overriding its default value.
  • Function Value Return

Similar to how we can pass values to a function through arguments, a function can also return a value when called. In this section, we will check out how a function can return a value.

To return a function value, we have to define it using the return statement. It exits a function and optionally passes an expression back to the caller. If no argument is defined for the return statement, then it returns None.

Have a look at the following code:

Run the code:

Here:

  • The function square() takes an integer x as the argument. Inside the function, it stores the square of x into y. Using the return statement, we return the value of y (an integer).

What would happen if we didn’t include the return statement? The next example perfectly demonstrates the result. Just comment out the return statement and run the code:

As explained before, it simply prints None as the print() function had no value to print on the screen. We could say that None is the default return value of the print() function.

Here is another example of using the return statement to return a value when the function is called. In this case, however, we are going to return the value of multiple variables. Take a look at the code:

Run the script:

Here:

  • The function add_numbers() takes three integer values as arguments and performs some calculations based on them.

  • Using the return statement, we are returning the value of three variables a, b, and c.

  • When the function is called later, the return value is stored in a variable sum.

  • Finally, using the print() function, we are printing the result on the screen.

However, the return statement comes with a catch. It causes the function to halt its operation and exit the moment it’s executed. So, you have to be really careful about the placement of the return statement.

The following code demonstrates this perfectly:

Next, run the script:

Here:

  • The function random_loop() runs a for loop from x = 0 to x = 25.

  • However, upon reaching x = 5, it executes the return statement. This halts the execution of the function completely and exits. Note that similar actions can also be performed with the break, continue, and pass statements.

  • As a result, the line This line won't be executed won’t be printed on the screen. Any code that exists after the return statement will be ignored.

This is why it’s recommended to set proper conditionals to check if it’s a proper time to execute the return statement.

Step 3 – Using the main() Function

Python allows calling functions at the bottom of the script and it will run as it’s supposed to. However, many programming languages like C/C++ and Java, etc. require a main function to execute. Though not mandatory in Python, using the main() function provides a logical framework for the program. Generally, the main() function contains the important components of the program. It can also help non-Python programmers understand the program structure easier.

Let’s start by defining the main() function. The structure will be as follows:

Next, add some code for the main() function to execute:

Save the changes and run the Python script:

Here, the main() function acts similar to any other function we’ve demonstrated so far. For the next step, we need a brief lesson on the variable scopes. A variable can have two scopes: global and local. A global variable is accessible by all functions in the code. A local variable, however, is only accessible by its parent function.

In Python, __main__ is a specific scope that holds the top-level codes for execution. When running a program (from standard input, interactive prompt, or script), its __name__ __name__  is set to __main__.

This is why it’s a convention to use the following construction:

There are a couple of different benefits to this approach. For example, it allows program files to be used in different ways:

  • If the if statement is followed, then it’s used as the main program.
  • If the if statement isn’t followed, then it can be used as a module.

Any code not contained within this statement will execute upon running the script. If you intend to use the program file as a module, then this statement will keep the code executions in check.

Time to put this new concept into action. Have a look at the following code:

Run the script:

Here:

  • We set a global variable name that stores a string value. It’s executed first when the script runs as it’s not gated by the if statement that checks for the value of __name__.

  • The function contains_vowel() checks the content of variable name, makes a logical decision, and prints a string on the screen.

  • The function print_letters() iterates through each character of the string and prints it on the screen.

  • Both contains_vowel() and print_letters() are called under the main() function.

  • Using the if statement, we decide to call the main() function only when the value of __name__ is __main__.

We called the functions contains_vowel() and print_letters() through the main() function. As we are working on Python, we are allowed to omit the main() function and call them directly as a normal function. The altered code would look like this:

Run the code:

Final Thoughts

In this guide, we demonstrated the fundamental concepts of functions in Python with examples. Functions are blocks of instructions that can perform actions within a program. Using functions properly makes the code reusable and modular.

Check out our various Python tutorials to further your understanding of programming with the Python language:

Happy Computing!