Python Functions Complete Tutorial

In this section we will learn what Functions are and how to use them in Python.

Python What is a Function?

Function is a block of code with a name tagged on it. The instructions in a function is something that we put for it.

We use functions when there are a set of instructions in a program that are needed in multiple places. So instead of writing the entire instructions in every place again and again, we put them in a function and just use the name of that function in other places.

Now whenever the execution engine reached the name of the target function, it knows that it should go and find the content of that function and execute them.

Basically, using functions we can stop a source code from copying the same sort of instructions in multiple places. This way, in later times if a change was needed on the source code, we only need to change the instructions in one place and that’s only within the body of the function!

Python Syntax and Definition: Defining a Function in Python

This is how we create a function in Python:

def functionName(parameter1, parameter2, parameterN):

#body…

:: the body of a function starts from the colon of that function and the entire indented line below that function will be part of this function. This means whenever the function is called, any instruction within this body will be executed.

Python def Keyword

First and foremost, in order to create a function, we start with the keyword def.

Function Identifier in Python

After the keyword def comes the name of the function which is known as the function identifier.

This name could be a combination of letters, numbers and underscore _.

Note: The name of a function should start with either underscore or letters! But not numbers.

Function Parameters in Python

After the name of a function there’s a pair of parentheses. We use this parenthesis to create parameters!

You might be asking what are parameters and why we need them anyway?! Well, parameters are nothing but variables that are local to the target function. We use parameters when the function needs input data in order to work properly.

For example, if the work of the function is to take 2 input values and then return the multiplication result, then obviously this function needs 2 input value in the first place, right?

So what we do here is to set two parameters in the pair of parentheses and they will hold the two input values when the function is called later in the program.

Note: each parameter is separated via comma , from the other parameter.

Be aware that the use of parameters for a function is optional! That means if a function doesn’t need input values, then we can just put an empty pair of parentheses after the name of a function and that’s it. But remember, the use of pair of parentheses for a function is necessary no-matter if the function takes input values or not.

Example: Python function with multiple parameters

def multiply(val1, val2):
print(val1*val2)
multiply(10, 40)
Output:
400

Here the name of the function is multiply and it has two parameters named val1 and val2. As mentioned before, these two parameters are the local variables of the function. This means we can access these parameters within the body of the function but not outside of the function!

Within the body of the multiply function the instruction is basically saying: when the function is called, there are two input values expected; take those values, put the first value into the val1, put the second value into the val2 and then multiply these values to each other and send the result to the output stream.

Note: by default, a function should be called first so that the execution engine goes and run its body. As you can see in the example above, in order to call a function, we use the name of a function + a pair of parentheses on the right side of it and inside that parentheses we put the input values depending on the number of parameters that the function has.

For example the multiply function has 2 parameters and so we need to pass 2 input values (each separated via the comma ,) to this function.

If we put less or more input values, we will get error instead!

What is argument in Python?

The value we pass to a function when the function is being called is known as the argument of that function.

Example: setting parameters for Functions in Python

def multiply(val1, val2):
print(val1*val2)
multiply(10, 40)
Output:
400

For this example, the multiply function has two parameters and so we passed two arguments when called the function. These arguments are 10 and 40.

Calling a Function in PYTHON: How to Call a Function in Python?

In order to call a function in a program, use the name of the function and then put a pair of parentheses after that name. Inside these parentheses put any argument that the function needs.

Example: calling a function in Python

def sayHi(name):
print(f"Hello {name} :)")
sayHi("John Doe")
Output:
Hello John Doe 🙂

Here the name of the function is sayHi. It has one parameter and so it takes one argument as a result.

So we called the function name and put a pair of parentheses on the right side of this function and passed one argument to it.

Note: this argument will then be assigned to the name parameter of the function and so this parameter actually points to the argument we’ve passed to the function.

Types of Arguments in Python

There are two ways of passing arguments to a function in python:

  • Positional Arguments

  • Keyword Arguments

Python Positional Arguments

The positional arguments are when we call a function and pass arguments to the function in the same order as the parameters of that function.

In this model, the first argument will be passed to the first parameter of the function, the second argument to the second parameter and so on…

Example: using positional arguments in Python

def printName(name, lastName):
print(f"Hello {name} {lastName}:)")
printName("John", "Doe")
Output:
Hello John Doe:)

Here the first argument John is passed to the name parameter. And the Doe argument is passed to the lastName parameter.

Python Keyword Arguments (Named arguments)

The second way of calling a function is by using the name of parameters when passing the arguments to the function.

For example, if the function has two parameters named firstName and lastName, then when calling the function, we use the name of the parameters as if they were a variable and we’re assigning values to those variables like:

functionNaem(firstName = “John”, lastName = “Doe”)

Note: when using the name of parameters when calling a function, the order is no-longer a matter!

For example, if the first parameter is firstName and the second parameter is lastName then using named arguments, we can first assign the value of the lastName and then pass the value of the firstName.

Example: using keyword arguments in Python

def printName(firstName, lastName):
print(f"Hello {firstName} {lastName}:)")
printName(lastName = "Doe",firstName = "John")
Output:
Hello John Doe:)

Python return Statement

Functions are capable of returning a value when we call them.

In order to make a function to return a value, we use the return statement.

Put any value on the right side of this keyword and that will be returned when the execution engine reached to this statement within the body of the function.

Note: using the return statement will terminate the work of a function as well. This means if we put any statement after the return statement, that will not execute because Python execution engine considers the return statement as the terminator or the last statement of a function.

Example: using return statement in python

def addition(firstValue, secondValue):
return firstValue + secondValue
res = addition(50, 70)
print(res)
Output:
120

Here the addition function takes two arguments, add them together and returns the result using the return statement.

So we called the function and passed the result to the res variable.

At the end, passed the value of the res variable to the print() function and this value appeared on the output stream.

Python Local variables

Local variables are those that we put within the body of a function. These values are local because outside of the body of the target function is as if the variable does not exist at all! Basically, if we attempt to access a local variable outside the body of the target function, we will get an error (unless there is another variable with the same name and outside of the body of the function).

Example: creating local variables in Python

def addition(firstValue, secondValue):
result = firstValue + secondValue
return result
res = addition(50, 70)
print(result)
Output:
NameError: name 'result' is not defined

Note that in this example, there’s a local variable named result within the body of the addition function. But we’ve tried to access the result variable from outside using the print() function! So because a local function is limited to its enclosing function and we tried to access such variable from outside, we got NameError error then.

Python Global Variables

If we declare a variable outside the boundary of any function, that variable will be known as the global variable. We call it global variable because any function in that program can access the variable and make the variable to point to another value if needed.

But in order to access a global variable from within the body of a function we need to make that function to aware that the target variable already exists and it’s a global variable.

We do this using the global keyword.

Let’s dive into an example and we will continue the global discussion after the example:

Example: creating global variables

gVariable = 1000
def fOne():
global gVariable
gVariable = 100
def fTwo():
global gVariable
gVariable = 200
fTwo()
fOne()
print(gVariable)
Output:
100

Here there’s one variable named gVariable and because this variable is declared outside of any function and block, so it is a global variable.

Now inside the functions look that the first statement is a call to the global gVariable! This statement basically tells the Python execution engine that the variable is global variable and so we’re attempting to change its value and not create a local variable with the name gVariable.

So here when we first called fTwo() function, the value of the gVariable changed from its initial value to 200. After that when we called the fOne() function, the value of the gVariable again changed from 200 to 100.

That’s why when at the end we called the gVariable in the print() function, the value 100 got printed to the output stream.

Note: if the purpose of using a global variable inside a function is to just access the value of the variable, then we don’t need to declare the global variable in that function first! We can simply call the target variable and get its value.

Python Global Variable in Function

You should know that using the global keyword in a function and behind a variable name, will make that variable as global. Basically, that means if there’s no such variable in the global scope (with the same name) then the execution engine will create a global variable with that name and assign the target value to it.

Let’s see this in the example below.

Example: using global variables in python functions

def fOne():
global globalVariable
globalVariable = 100
def fTwo():
global globalVariable
globalVariable = 200
fTwo()
fOne()
print(globalVariable)
Output:
100

Note that there’s no globalVariable in the global scope here! But within the fTwo() function (which is the first function call in our example) the first statement is global globalVariable = 200.

When the execution engine sees this statement, it will first check the global scope to see if there’s a variable with the name globalVariable. If it could not found one, it will create a new one as a result.

After that, in the second statement in the fTwo() function, the value 200 will be assigned to the globalVariable that is created on the global scope.

Now when the fOne() function is called, the execution engine once again checks the global scope to see if there’s a variable named globalVariable. This time because there’s one (as a result of calling the fTwo() function, this variable is now created) so the execution engine uses that variable to be used in the body of the fOne() function and won’t create a new one anymore.

So in the last statement in fOne() function, the value 100 is assigned to the globalVariable. That’s why we could call the print() function as the last statement of the program and send the value of this variable to the output stream.

Python Functions as Arguments to Other Functions

In Python, functions are also objects! This means the name of a function is just a variable that points to a memory location where the actual body of the function is stored.

This means just like variables, we can make a variable or a parameter of a function to point to the same function as the name of that function is already pointing to.

To do this, all we need to do is to pass the name of a function to another variable or as the argument of another function.

Example: passing a function to another variable in Python

def funcOne():
print("The message is coming from funcOne function")
funcRef = funcOne
funcRef()
Output:
The message is coming from the funcOne function

As you can see, the funcOne identifier is pointing to a function in this example. Now we’ve passed the funcOne to the funcRef variable. This will cause the funcRef to point to the same function as the funcOne. For this reason, we could use the funcRef variable to call the function that funcOne is pointing to as well.

Example: passing functions to other functions as arguments

def funcOne():
print("The message is coming from funcOne function")
def funcTwo(refFunc):
refFunc()
funcTwo(funcOne)
Output:
The message is coming from funcOne function

Note that when passing the name of a function to another variable or parameter, we don’t use the pair of parentheses anymore! If we do, the function will be called and the result of that function (if any) will be passed to the target variable or parameter instead.

Difference between Parameter and Argument

A parameter is the variable that we define for a function within its pair of parentheses and they act as the local variables of the target function.

On the other hand, arguments are the values we pass to a function and they will be assigned to the parameters of a function.

More to Read:

Inner Functions in Python
Python Return Statement
Python Optional Arguments
Python Closure
Python Lambda
Python Functions and Single Asterisk * Operator
Python Functions and Double Asterisk ** Operator