Introduction to Function in Python

Software creation is challenging as it requires thousands of lines of code, and as the length of code increases, this challenge becomes tougher. Hence, software engineers separate their codes into numerous functions so that the code length gets reduced and tracking bugs becomes easy. Likewise other programming languages, Python also provides support for writing functions, and it has mainly two types: User-defined and In-built functions. 

In Python, functions are required to follow specific syntaxes to ensure their validity inside any program. In this article, we will discuss more basics of Python functions.

Key takeaways from this blog

After going through this blog, we will be able to understand the following things:

  1. What are Python functions and their advantages?
  2. How to create a Python function?
  3. How to call a Python function?
  4. What are the various function arguments?
  5. Use of return statement in Python function.
  6. The Anonymous function.

So let’s start by knowing more about python functions.

What are Python functions and their advantages?

Python functions are a set of instructions grouped in a block, and this block gets executed only when it is called inside our program. Instead of writing the same code for different input variables over and over, programmers write separate functions and call them for different inputs.

Advantages of Python functions

Among many, here are some practical benefits that any Python function provides:

  • The code length becomes short, cleaner, modular, and organized.
  • Defined functions can be used anywhere in the program.
  • Tracking of bugs can be quickly done inside a program.
  • We can get as many outputs as we want with varying data types.

Now that we know about the functions, let’s learn how we can create them.

How to create a Python function?

In any programming language, we need to follow some defined pattern in which code should be written, and Python is not an exception here. We need to follow the defined syntax in which we can write Python functions, so let’s first learn about this syntax itself.

def function_name(inputs):
    # Statements
    return

Structure of a Python function


The structure of a Python function is shown in the above image. Major components that are part of it are:

  • Keyword “def”: It is the short form of the definition that marks the start of a function header.
  • Function name: It is the name of the function using which it will be called anywhere else in the program. This name should be unique so that our programs know which function they need to call.
  • Input to the function: We send arguments using parameters, using which function executes the internal statements. These arguments are optional, and we will learn more about this in a while.
  • The header of a function is terminated by a colon ( : ).
  • Docstring: In large code bases, programmers write some description about the functionality of that function. This description is a document string and, in short, a “Docstring”.
  • Statements: In the definition of Python functions, we said that a function is a block of sequential statements executed whenever we call any function. These sequential statements must be valid as per Python coding Syntax.
  • return: Finally, to come out of the functional block, we need to pass a return statement. This return statement can be empty or contain one or multiple values belonging to various data types in Python. As Python has an indentation-based workflow, sometimes we can skip the return statement.

Example

Let’s create a function that calculates the square of any given number passed as an input to that function.

def calc_square(num):
  
    square = num**2
    
    print("The square of %d is : "%num, square)
    
    return

There is another form of writing function where we explicitly mention the data type of input arguments and the return. Let’s see that also.

def function_name(var1 : int, var2: str, var3: float) -> int:
    # statements to be executed
    return variable

Now, as we have generated a function, let’s learn how to use it or call it inside our programs.

How to call a Python function?

Once a Python function’s framework is complete, we can call it anywhere in our programs. For example, earlier, we designed a calc_square function, and now we will call it for multiple input values.

calc_square(7)

# Output
The square of 7 is : 49

calc_square(10)

# Output
The square of 10 is : 100

If a Python function return values instead of an empty return like what we saw in the calc_square function, then we need to store the return in some variable. Let’s see one example corresponding to that also.

def calc_square(num):
    square = num**2
    return square
    
num = 7
sqr = calc_square(num)

print("The square of %d is : "%num, sqr)


# Output
The square of 7 is : 49

Now we know how these blocks of statements can be reused inside our programs. Let’s learn more about the types of these arguments using which we can call a Python function.

What are the various Python function arguments?

There are mainly three types of arguments:

1. Default arguments

These arguments are parameters already filled with some value in a Python function. For example:

def calc_multiply(var1, var2=7):
    multi = var1*var2
    return multi

The above function calculates the multiplication between two variables, var1 and var2. But var2 has a default value of 7. Let’s see how two types of calls will affect the result

# Type 1
multi = calc_multiply(11)
print(multi)

### Output
77

# Type 2
multi = calc_multiply(5, 9)
print(multi)

### Output
45

Please note that in type 1 calling, if we do not mention the value of the default variable, it will automatically consider the default value. But we can overwrite these default values by passing additional arguments, as shown in Type 2 calling. We must think about what will happen if we do not give any input value for the parameters with no default value. Let’s see:

multi = calc_multiply()
TypeError: calc_multiply() missing 1 required positional argument: 'var1'

Yes, it will throw a TypeError. It will suggest us fill the positional argument: ‘var1’ with some value. One interesting thing to note here is that the order of writing arguments should follow some basic rules per Python function syntax. One of those basic ones is the non-default arguments should be mentioned before the default arguments. So the example shown below will throw SyntaxError:

def calc_multiply(var1=7, var):
SyntaxError: non-default argument follows default argument

2. Keyword arguments

If we pass two values inside calcmultiply, it will, by default, treat the first value as var1 and the second value as var2. Input arguments into a Python function are linked to its name, and we can pass arguments out of order as well. For example, we call the same calcmultiply function like this:

multi = calc_multiply(var2=9, var1=5)
print(multi)

# Output
45

3. Variable length arguments

In Python functions, we can also pass a variable length argument using two special symbols:

  • *args : Non-keyword arguments
  • **kwargs: Keyword argument

Let’s see their examples for a better understanding:

# *args example
def cal_sum_of_arguments(**args):
    sum = 0
    for arg in args:
        sum += arg
    return sum
total_sum = cal_sum_of_arguments(1, 5, 7, 9, 11)
print("Sum of all arguments is : ",total_sum)

# Output
Sum of all arguments is :  33

# **kwargs example
def print_paired_arguments(**kwargs):
    for key, value in kwargs.items():
        print("Key = ", key, " value = ", value)
    return
print_paired_arguments(var1='Enjoy',var2='Algorithms', var3='ml')

# Output
Key =  var1  value =  Enjoy
Key =  var2  value =  Algorithms
Key =  var3  value =  ml

Use of return statement in Python function

The return statement exits the function and brings code execution to the line where that function was called. Using the return statement, we can extract specified values from a function. In Python, we have the flexibility to return multiple values of varying data_types from a function. For example:

def print_paired_arguments(**kwargs):
    keys = []
    values = []
    for key, value in kwargs.items():
        keys.append(key)
        values.append(value)
    return keys, values

keys, values = print_paired_arguments(var1='Enjoy',var2='Algorithms', var3=3)

# Output
keys = ['var1', 'var2', 'var3']
values = ['Enjoy', 'Algorithms', 3]

Pass by reference vs. pass by value

In Python programming, everything is an object, and variables are the reference to these objects. But when we pass these variables as input arguments, a new reference to that object is created. This can be tricky to understand but let’s see this via an example.

def referencing(var1):
    var1[0] = 7
    return
var = [1, 0, 3, 4, 7, 9, 11]

referencing(var1=var) # here var1 is a new reference to the same var
print(var)

# Output
[7, 0, 3, 4, 7, 9, 11]
## Please note that the var got changed as we are modifying the object present at the same reference.

But when we try to modify the var1 to something else altogether, it will start referencing some other object, and the link between previous and current referencing will break. Let’s see that with an example.

def referencing(var1):
    var1 = [7, 9, 11, 12, 3, 4, 5]
    return
var = [1, 0, 3, 4, 7, 9, 11]
referencing(var1=var)
print(var)

# Output
[1, 0, 3, 4, 7, 9, 11]
## Please note that the var did not change as we are modifying the reference itself.

The Anonymous Function (lambda function in Python)

In Python, we have functions that exist without a name. We use the def keyword for functions with a name, but for anonymous functions, we use the lambda keyword. A lambda function can take any number of input arguments but always returns one value resulting from that function. So we can say that a lambda function needs one expression, so a print statement can not be passed as it will not output anything.

lambda_ = lambda var1, var2, var3: var1 + var2*var3
lambda_(1,2,3)
# Output
7

Commonly used Inbuilt Python Functions.

As we said, there can be mainly two types of Python functions, 

  • User-defined functions: The custom functions that we want in our codes to perform some specific tasks
  • Predefined functions: There are some famous predefined functions frequently used in Python programming. Some of them are:

len()

This function gives us the length of the variable passed as an argument of this function. For example:

var1 = "This is a pen"
print(len(var1))

# Output
13 ## Because there are 13 characters in the variable var1


var2 = [1, 3, 5]
print(len(var2))
# Output
3

More Examples

1. type([1, 2, 3])  # Type function shows the data type of the var
# <class 'list'>
2. tuple([1, 2, 3]) # Converts valid input into a tuple
# (1, 2, 3)
3. str(7) # Converts valid input into a string
# '7'
4. round(6.6) # Round off the valid input variable 
# 7
5. list(reversed([1, 2, 3])) # reverse the list
# [3, 2, 1]
6. range(0,7) # We discussed this function in detail already
7. print() # prints the input passed 
8. int() # converts the input into int
9. sorted() # sorts the list in ascending order
10. list() converts the input into a list

Conclusion

In this article, we discussed one of the basic concepts In Python programming, i.e., Python Function. We learned how to create a function and call it into our program. We also discussed the input arguments in greater detail with examples. Last, we saw some in-built python functions frequently used in Python programming. We hope you enjoyed the article.

Next Blog: Introduction to OOPS in Python

Previous Blog: Introduction to loop in Python

Enjoy Learning!

Share feedback with us

More blogs to explore

Our weekly newsletter

Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.

© 2022 Code Algorithms Pvt. Ltd.

All rights reserved.