Python Functions for Reducing Code Complexity

By:   |   Updated: 2024-06-12   |   Comments   |   Related: > Python


Using Python functions allows you to solve the problem of having to write repeated code, make code easier to understand, and reduce code complexity. In this tip, we look at how to create Python functions.


Functions are an excellent way to divide large programs into small pieces of code that perform a specific task. You can reuse these functions without rewriting the code inside them. Suppose you create a function to validate input values. Now, while executing the main program, you can call this function to perform that specific task.

We can divide Python functions into two categories:

  • Built-in functions
  • User-defined functions

Let's explore these Python functions in detail.

Built-in Functions

Python has several pre-defined functions that you can use without writing any code. These functions are known as built-in functions. A few built-in functions are listed below:

  • Print(): prints message to the console.
  • len(): checks an object's length or number of items.
  • range(): generates a sequence of numbers.
  • type(): returns the object or data type in Python.
  • input(): takes user input for the given parameter.

User-defined Functions

Any function created by a developer to execute code is known as a user-defined function. We need to define a function with the def keyword.

The following diagram shows a basic Python function:

def myfunction():
    print("Welcome to python functions")
basic Python function

As explained above, we created a function, myfunction(), to print a message using the print built-in function. You can call this function anywhere in the code to print this message.

Indentation is a must for defining code in Python functions. If you try to run the code without indentation, it gives an error:


Functions with Arguments

You can have a user-defined function with or without the argument. In the earlier defined myfunction(), we used no argument.

Suppose we want to calculate the sum of two numbers using a Python function. We need to have two argument values passed to the function.

In the following function, we define the function with parameters as sum(a,b). We can pass the argument's value by calling the function a sum(10,20).

def sum(a,b):
    result = a + b
    print(f"The sum of numbers {a} and {b} is: {result}")
Functions with arguments

Types of Arguments in a Function

We can have the following types of arguments in a function.

Default Argument

We can specify a default value for an argument in the function. If we call the function without any explicit argument value, the function executes with the default argument; otherwise, the explicit argument will take precedence.

The following code defines the default argument values as a=0 and b=0. If we directly call the function sum(), it returns 0; if we pass the explicit value sum(1,5), it returns 6.

def sum(a=0,b=0):
    result = a + b
    print(f"The sum of numbers {a} and {b} is: {result}")
Default argument

Arbitrary Arguments

We can use the * keyword in the function to accept n number of arguments. For example, let's convert the sum function for the arbitrary argument.

In the function below, we specify the argument as *numbers and the logic for adding the numbers. Now, we can specify the number of arguments, and the function does the addition. For example, I have called the function with 2, 4, and 12 input values.

def addition(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n
    print("Sum:", sum)
Arbitrary Arguments

Keyword Arguments

If you have multiple parameters defined in a function, you need to pass the arguments value in the same order as it is defined. However, what if you want to mix the order of arguments? Let's look at below example:

def emp(first_name,last_name,age):
    print("Employee:" +  first_name + ' '+ last_name, age)

In this example, we pass the argument name while calling the function. Therefore, the position of the argument does not matter. All Python functions below return the same output irrespective of keyword positioning.

Keyword Arguments

However, the positioning matters if you do not use argument names. By default, the first argument is mapped to the first value, the second argument is mapped to the second value, and so on.

positioning matters

What if you mix the keyword argument and positional argument? In the example below, we defined the last_name and age argument names but did not specify the first_name. Therefore, Python maps the positioning argument first and then takes the keyword argument.


However, if you change the code to specify a positional argument after a keyword argument, Python generates an error, as shown below.


The Return and Pass Statement in Python Functions

Return Statement

A Python function uses the RETURN keyword to return a single or multiple values from the function. By default, the function does not return any values.

In the below Python function, we use the return keyword to return the value of the variable sum.

def addition(a,b,c):
    sum = a+b+c
    return sum

Similarly, we can return multiple values from a function. For example, in the code below, we calculate addition, subtraction, and multiplication from inputs n1 and n2. It returns the values of the variable add, sub, and multiply.

While executing the function, we can assign these multiple return values to the different variables and use them in subsequent code. For example, the first return value add is assigned to a, and the second return value sub is assigned to b.

def maths(n1,n2):
    add = n1 + n2
    sub = n1 - n2
    multiply = n1 * n2
    return add, sub, multiply
a, b, c = maths(10, 2)
print("Addition: ", a)
print("Subtraction: ", b)
print("Multiplication: ", c)
The Return and Pass Statement in Python Functions

Pass Statement

We can use the pass statement to skip executing the code.

In the example below, we want to print a message if the number is positive; otherwise, skip the code execution. Therefore, we specify the pass keyword in the else condition.

def passexample(input_value):
    if input_value>0:
        print("positive number")
Pass Statement

Recursive Function in Python

If a function calls itself repeatedly, it is called a recursive function. Suppose we need a Fibonacci sequence that generates a pattern where each number has a sum of the two preceding numbers.

The following code takes the input for num and recalls the function repeatedly until its value is less than or equal to 1.

def fibonacci_series(num):
    if num <= 1:
        return num
        return fibonacci_series(num - 1) + fibonacci_series(num - 2)
for i in range(10):
Recursive Function in Python
Next Steps
  • Stay tuned for more Python tutorials in upcoming tips.
  • Explore existing Python tips on

sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip

About the author
MSSQLTips author Rajendra Gupta Rajendra Gupta is a Consultant DBA with 14+ years of extensive experience in database administration including large critical OLAP, OLTP, Reporting and SharePoint databases.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips

Article Last Updated: 2024-06-12

Comments For This Article

get free sql tips
agree to terms