python function

Table of contents:

  1. What are Python functions?
  2. User-defined functions vs Built-in functions
  3. Defining a function
  4. Function arguments
    1. Required arguments
    2. Keyword arguments
    3. Default arguments
    4. Variable-length arguments
  5. Conclusion
In this tutorial, we’ll learn about the different Python functions and how to define them. We will learn how functions work and why they are useful. Moreover, we’ll also look at different mechanisms for passing arguments and learn how to return data from our function.

What are Python functions?

A function in Python is a set of related statements that are designed to perform computational, logical, or evaluative activities. Functions can be built-in or user-defined. The concept is to group numerous frequent or repetitive processes together and create a function so that instead of writing the same code over and over again for different inputs, we can make function to reuse the code it contains again. This helps the program to be concise, non-repetitive, and well organized.

User-defined functions vs Built-in functions

Built-in functions are those that are already defined in Python libraries and we can call them directly. For example, ‘print()’ is a built-in function that shows code output. User-defined functions are those we define ourselves in our program and then call them wherever we want. We define a user-defined function with the keyword ‘def’ followed by the function name.

Defining a function

We can create a Python function using the keyword def. After creating a function we can call it using the function name followed by parentheses containing the parameters of that particular function. Syntax of user-defined function:

def function_name(parameter_s):
    statement_s
    return expression
The function components are explained in the table below:
Component Function
def Keyword ‘def’ informs about the beginning of the function header
function_name Identifier that refers to the function’s name
parameters (Addition) Parameters (arguments) are an optional comma-separated list through which we can pass values to a function
: A colon (:) to indicate the end of the function header
statement_s One or more Python operators which make a function body
return expression An optional return operator to return a value from the function.

Now let’s see the example of basic user-defined function.


# A simple Python function
def func():
    print("It is a user-defined function.")
# Driver code to call a function
func()
Output:
It is a user-defined function.
  It was an example of the simple user-defined function in Python.

Function arguments

The arguments are the values specified between the parentheses of the function. A function can take as many parameters as it likes, separated by commas. When we want to pass data to a function so that its behavior changes from one call to the next, we use arguments. Even if we create a function that takes no parameters, parentheses must still be present, even if they are empty. We can call a function by using the following types of arguments:
  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments
In this tutorial we will look at each type separately and create functions using different arguments.

Required arguments

Required arguments or also called positional are arguments passed to the function in the correct positional order. The number of arguments in the function call must exactly match the function definition. Let’s see the example of calling required arguments in the user-defined function:

# Definig a function passing arguments 'num','item','price' 
def func(num, item, price):
    
    # Printing using arguments of the funtion
    print(f'{num} {item} cost ${price:.2f}')
    
# Specifying a corresponding list of arguments     
func(5, 'watermelons', 3.69)
Output:
5 watermelons cost $3.69
 

Keyword arguments

When we use keyword arguments in a function call, the caller identifies the arguments by parameter name. This allows us to skip arguments or place them out of order, as opposed to using positional arguments. For example, previously defined function can be called using keyword arguments:

# Definig a function passing arguments 'num','item','price' 
def func(num, item, price):
    
    # Printing using arguments of the funtion
    print(f'{num} {item} cost ${price:.2f}')
    
# Calling arguments by keywords    
func(item = 'watermelons', num = 5, price = 3.69)
Output:
5 watermelons cost $3.69
  So, as you can see by using keyword we can easily call arguments no matter of their position.

Default arguments

A default argument is one that takes on a default value if no value is specified in the function call for that argument. The following example illustrates the concept of default arguments.

# Definign a function
def inf( name, age = 20 ):
    print("Name:", name)
    print("Age:", age)
    return

# Calling inf function
inf(age=18, name="Alsu" )

# Calling inf function where age is missing
inf(name="Mia" )
Output:
Name: Alsu Age: 18 Name: Mia Age: 20
  In the output and code above we see that in the place where age for Mia was missing by default it took value of 20.

Variable-length arguments

It is possible that we will need to process a function for more parameters than we provided in the function definition. Variable-length arguments, unlike required and default arguments, are not listed in the function definition. Using special characters, we can send a variable number of parameters to a function. There are two special characters:
  • *args (no-keyword arguments)
  • **kwargs (arguments with keywords)
A function with variable parameters and no keywords has the following syntax:

def function_name(formal_args, *var_args_tuple ):
    function_body
    return expression
Before the variable name that carries the values of all nonkeyword variable parameters, an asterisk (*) is put. If no extra arguments are supplied during the function call, this tuple remains empty. Here is a simple example:

# Defining a function with no-keyword argument *vartuple
def num(arg, *vartuple):
    print("Output is: ")
    print(arg)
    for var in vartuple:
        print(var)
    return

# Calling a function num
num(1)
num(7,6,5)
Output:
Output is: 1 Output is: 7 6 5
 

Conclusion

As we discussed that a function in Python is a set of related statements that are designed to perform computational, logical, or evaluative activities. In this tutorial, we learnt the difference between built-in and user defined function. Moreover, we covered  how to define a function calling different types of arguments.
Leave a Reply