This is a detailed tutorial on Python Functions. Learn different properties of functions such as definition & calling and keyworded/non-keyworded arguments.
In any programming language, functions are basically blocks of code that execute only when they are called. Apart from this, the two other major features associated with functions are that they can be passed data using parameters (arguments) and they can also as the result of internal block code processing, they can return data.
Functions are good for code-reusability. You can write a generic piece of code once and can use it again and again whenever required in your entire python program.
Defining a Function
Python allows you to create function easily using the
def keyword. You have to start writing a function with the keyword
def followed by the name of the function and then with a semicolon and new line Tab space, you can start writing the code inside the function block. This is exactly how you create blocks in python for loops, while loops and if-else statements.
The basic syntax for function definition is given below.
#Function's Code Block
#Write Function's code Here
If you’re writing more than one argument for the function, then they must be separated with commas.
Note. You may or may not provide arguments to the function. Arguments are always optional. You can definite a function to have one or more, keyworded as well as non-keyworded arguments. We’ll learn more about arguments later in this article.
Calling a Function
The functions must be defined before they can be called in your code. Once you’ve defined a function in your python program, you can call it at any line after it has been defined. The syntax to call a python function is quite easy and is written below.
#Calling a Non-Parameterized Function
#Calling a Parameterized Function
functionName(paramter1, paramter2, ...)
The following example illustrates how you can call a simple function that prints a string.
print("Hello! How are you?")
In the above code snippet, a function named
sayHello() is defined and then it is called. Inside the function block, we’ve just written a single print statement. Now you can see in the output screenshot, that print statement is being executed when I call the function.
You can pass data to the function using arguments. Arguments and parameters are quite similar terms and actually both of these refer to the data that is being passed to the functions, but there’rs a slight difference which we’ll clarify soon. But let’s just discuss how you can use define a function with arguments and how you can call a function with arguments.
Arguments are defined in the parenthesis written just after the function name. A function can be set to accept any number of arguments. But you must define all of the arguments before you can actually call that particular function with those arguments. Let’s understand the concept of arguments with the help of an example.
Example. In the following code snippet, we’ve defined a function that accepts two different parameters,
def printBio(name, age):
print("Your name is " + name + " and you are " + str(age) + " years old.")
printBio("Gurmeet Singh", 21)
printBio("Amandeep Singh", 12)
In the above code, we’ve defined a function named
printBio() and we’ve set the function to accept two parameters,
age. Then I’m calling the function twice with different parameters. Accordingly, in each of these calls, different data is being passed to the function and hence different string is being printed.
Note. If you’re just passing the values like the above example to call the function, then make sure you must write the passed arguments in the same order as they are defined in the function, otherwise, the value of one argument may be passed to another one and this way error may occur.
These types of arguments are known as non-keyworded arguments as we’ve not used any keywords to pass the parameters. You can pass the arguments in any order if you make use of the keyworded arguments, which we’ll discuss in the next section of this article.
Important. You can pass arguments belonging to any of the data types. Arguments are not limited to textual or numerical values. Even the iterables like list and tuple and custom data types can also be passed as arguments.
Parameter Vs. Arguments
It hardly matters what term you say but actually the parameters are the variables that are written in the parenthesis during the function definition while the arguments are the variables or the values that are being passed to the function during the call.
So, in the above example code, the variables name and age written in the function definition are perimeters while the passed values,
"Gurmeet Singh" and
21 are actually the arguments.
When you define a python function with arguments, you define a name each of the arguments and that name is the keyword or the variable with which that argument is being identified within the block code of the function. While passing arguments during the function call, if you do no make use of these arguments to pass the data, then the order of the passed arguments must be the same as the order of the defined arguments.
But you can pass the arguments during the function call if you’ll also use the argument keywords.
Example. The following example illustrates the use of keyworded arguments to call the function.
def printBio(name, age, score):
print("Your name is " + name + " and you are " + str(age) + " years old.")
print("Your score is " + str(score))
printBio(score = 99.5, name = "Gurmeet Singh", age = 21)
#Non-Keyworded Arguments, Order must be same as the function definition
printBio("Gurmeet Singh", 21, 99.5)
In the above code snippet, we’ve defined a function with three different arguments. Now, we’re calling the function. I’ve used the keywords in the first call to pass the arguments and you can clearly see the order of the arguments is different from the order of the arguments in the original definition of the function.
But as we’ve used the keywords to pass the arguments, the right parameters get the right data. In the next call, you can clearly see, we’ve not used any keywords for the arguments, so the order of the arguments has to be the same to avoid mixing up the data from one argument to another.
Number of Arguments
You can define a function to accept as many arguments as you want. Once you define a function with your desired number of arguments, say
x, then you must provide all of these
x arguments during the function call. The number of arguments in either keyworded or non-keyworded arguments function call must be exactly the same as the number of arguments defined in the function, not one less, not one more.
There’s an exception and that’s in the case if your defined arguments contain a default value, which we’ll discuss in a later section of this article.
Variable Number of Arguments
You can also define a python function that has the ability to accept a variable number of arguments. Both keyworded, as well as non-keyworded arguments, can be passed to a function that is defined to accept a variable number of arguments. For this, you’ve to make use of *args and **kwargs syntax.
I’ve already written a detailed article on the use of these syntaxes. Here’s the link to the article given below.
As I mentioned earlier in this article that you can set a default value for any of the function parameters. This way you get the choice of passing the value or not passing the value for that parameter as an argument during the function call. Let’s say there are four parameters defined in a function and one of them is a default parameter having a default value set for it.
Now you can either pass all the four arguments during the function call or can skip passing the argument which already has the default value set. In case you do not pass the value for such an argument, the default value will be picked up for that particular parameter to be used inside the function block of code.
Example. The following example is illustrated to clear the concept of default parameters.
def hello(name, score = "Not Known"):
print("Hello " + name + ", you score is " + str(score) + ".")
hello("Gurmeet Singh", 99.5)
So, in the above code, I’ve defined a function named
hello() and it accepts two parameters,
score. The parameter
score has a default value, so you may or may not pass it during the call, it’s optional. Now, in the first call, I have passed the values for both of the values and hence it prints the string according to both of the passed values but in the second I do not pass the value for the parameter
score as an argument, so it automatically picks up the default value and uses it in the print statement.
Note. The default parameters are also sometimes called optional parameters as it is your choice to pass them as arguments during the function call or not.
Returning values is one of the main characteristics of a function. In python, you can return values in the function using the keyword
return. The keyword for returning function values is the same in most of the other programming languages as well. The returned values can be stored into python variables.
Example. It will be better to understand the use of the return statement with the help of an example.
def add(x, y):
z = x + y
def multiply(x, y):
z = x * y
#Calling add() Function, it will print as print statement is used inside function body
#Calling multiply Function, it won't print as the return statement is inside the function body
#WORKS as multiply() function returns a value
multiplyResult = multiply(5, 3)
#WRONG as add() function do not return any value
addResult = add(x,y)
Only the highlighted lines of code (Line No. 10 and 17) prints the two output statements. Observe the code carefully to understand the proper usage of the return statement in a python function. The variable
addResult could not be assigned a value as the function add prints the value but does not return it. The function named
multiply() returns the value using the
return statement and hence while calling the function its return value can be stored in a variable.
Python functions can be declared empty but it raises an error if you will try to declare a python function without any code block. Therefore in case, you want the function to do nothing and contain no code to process, you can use the
pass Statement to still keep the function valid.
Example. The following example illustrates a valid empty function
trypass() and an invalid empty function.
#Valid Empty Function
print("Python Empty Functions")
#Invalid Empty Function
Observe the error in the output screenshot. This end of the file error is being raised by the invalid empty function written without the pass statement because the block for the function
trypass2() seems incomplete to the python compiler. Therefore, you must use the pass statement to create a valid block for the function to avoid this error and to keep the function still empty.
Recursion is the concept of calling the same function from within its own block of code. In other words, when a function’s logic code calls itself, it is termed as recursion. It is a very useful and functional approach to solve complex problems.
It is often used to solve the mathematical problems that require calculations which are further dependent on the data that has to first calculated and that the first calculated data again depend upon some other data that has to be yet calculation and so on.
But recursion is highly computing-intensive. Some of the recursion problems take a lot of processor time to complete its execution. The reason being the function can only complete its own execution after all of the dependent intermediate function calculations are complete.
Example. To understand the concept of recursion and how you can achieve it with Python Functions, make sure you observe the following example code carefully.
print("Function Called: writeBack(" + str(number) +")")
if number == 1:
print("Function Execution COMPLETE!")
number -= 1
A function named
writeBack() is defined and it takes one argument named
number. The first line of the function simply prints a string stating the function is being called with which value. It is simply to tell us which function is called. Then we’ve used the If-else statement. We’re calling the function if the passed argument is not one. In the else block, we’re decrementing the value by 1 and then again calling the function.
At line number 9, I invoked the function with passed argument 10. Now, in the output, you can see the order of execution. It keeps on calling the function is reverse order, illustrating very simple recursion.
The above code of recursion is just for example and actually it does not perform any complex calculation. A useful application of recursion is calculating the factorial of a number.
if n == 1:
It calculates the factorial of 10 with a recursion python function.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!