Functions In Python - Reusable Programs


In this tutorial, you are going to learn about functions in Python. This guide covers all useful concepts of Python functions with examples.

    Table Of Contents

  1. Python function
    1. Function syntax
    2. Defining a function
    3. Calling a function
    4. Functions Example
  2. Python Function Arguments
    1. Positional Arguments
    2. Keyword Arguments
    3. Variable length positional arguments
    4. Variable length keyword arguments
  3. Python Function Return
  4. Recursion
  5. Lambda Function
  6. Conclusion

functions in python

Python function

A function is named a block of code that performs a specific task.

It is defined to perform a specific task and call it whenever you need to perform that task.

It reduces the amount of code that needs to be written because you can reuse the same code multiple times just by calling it.

Functions are also used to make the code more modular, readable, easier to understand, and easier to maintain.


Function syntax

A function is defined using the def keyword. Here is the syntax:

def function_name(arg1, arg2, arg3):
    # function body
    return xyz

Defining a function

Use the def keyword, decide on a valid name and create the function following the syntax above.

# defining a python function
def hello():
    print("Hello World")

Your function is now defined but you have to call it to use it.


Calling a function

To call a function, use the function name followed by the parentheses. If there are arguments then separate it by commas.

# defining a python function
def hello():
    print("Hello World")

# calling the function
hello()

Output:

Hello World

Functions Example

Here are some useful examples of functions. These examples will let you understand python functions more clearly.

Example 1: A simple function that prints the string "Hello".

def hello():
    print("Hello")

hello()

Output:

Hello

Example 2: A function that takes a username and prints the string "Hello username".

def hello(username):
    print("Hello " + username)

hello("John")
hello("Annie")

Output:

Hello John
Hello Annie

Example 3: A function that takes 2 numbers and returns the sum of them.

def sum(a, b):
    return a + b

sum = sum(10, 20)
print(sum)

Output:

30

Example 4: A function that takes a list as an argument and returns the sum of all the elements in the list.

def sum(list):
    sum = 0
    for i in list:
        sum = sum + i
    return sum

list = [1, 2, 3, 4, 5]
print(sum(list))

Output:

15

Python Function Arguments

A function can take any number of arguments. These arguments are separated by commas.

The arguments are used to pass some data to the function. The data can be of any type string, number, list, tuple, dictionary, etc.

In the python function there are 4 types of arguments:

  1. Positional arguments
  2. Keyword arguments
  3. Variable length positional arguments
  4. Variable length keyword arguments

1. Positional arguments

Positional arguments are the normal arguments that are passed to the function. While calling the function, you have to pass these arguments in the same order as defined in the function.

Suppose our function be following:

def info(name, age):
    print("Name:", name)
    print("Age:", age)

The correct way to pass arguments: The function requires 2 arguments where the first argument must be name and the second argument must be age. So the correct way to call the function is like this:

info("John", "20") ✅

The possible wrong way to pass arguments:

If we change the order of the arguments the function will not output the correct result or may throw some error. Also if we pass more or fewer arguments, the function will throw an error.

info(20, "John") # ❌ wrong order
info("John") # ❌ less argument
info("John", "20", "30") # ❌ more argument

2. Keyword arguments

Keyword arguments are the arguments that are passed in pairs of key and value (keyword=value).

While calling the function, you can pass the arguments in any order. It is identified by the key.

Note: Positional arguments can't be used after keyword arguments. However, it can be used before keyword arguments.

The correct way to pass arguments: The function requires 2 arguments where the order of the arguments is not important as long as the key is correct. So the correct way to call the function is like this:

info(name="John", age="20") ✅
info(age="20", name="John") ✅

The possible wrong way to pass arguments:

The only wrong way is to pass more or fewer arguments. If we pass more or fewer arguments, the function will throw an error.

info(name="John", age="20", city="New York") # ❌ more argument
info(name="John") # ❌ less argument

3. Variable length positional arguments

Variable length positional arguments are the arguments represented by the * operator. It is used to accept any number of arguments. The arguments are separated by commas.

The standard way to represent this argument is *args.

Suppose our function be following:

def sum(*args):
    sum = 0
    for i in args:
        sum = sum + i
    return sum

The function can accept any number of arguments. The arguments are separated by commas.

sum(1, 2, 3, 4, 5) # ✅
sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) # ✅

4. Variable length keyword arguments

Variable length keyword arguments are the arguments represented by the ** operator. It is used to accept any number of key-value pairs.

The standard way to represent this argument is **kwargs.

The **kwargs is a dictionary of arguments represented by the ** operator. Example, {'name': 'John', 'age': '20'}.

Suppose our function be following:

def info(**kwargs):
    for key, value in kwargs.items():
        print(key, ':', value)

The function can accept any number of key-value pairs. The key-value pairs are separated by commas.

info(name="John", age="20") # ✅
info(name="John", age="20", city="New York") # ✅

Python Function Return

All python function returns something at the end of the function.

The return statement is used to return a value from a function.

def get_10():
    return 10

print(get_10()) # print returned value
# Output: 10

You can also save the returned value in a variable and use it later.

def get_10():
    return 10

number = get_10()
print(number)

Python can return any type of data. The return statement can be used to return a single value or a list of values.

def fxn1():
    # return string
    return "Hello"

def fxn3():
    # return boolean
    return True

def fxn3():
    # return list
    return [1, 2, 3]

def fxn4():
    # return tuple
    return (1, 2, 3)

As long as you can handle the python function can also return multiple different types of data in a single function.

# function returning 2 different 
# types of data in different situations

def fxn(num):
    if num % 2 == 0:
        return 1
    else:
        return "Hello"

If we don't return any value from the function, the function will return None.


Recursion

A function is called recursive if it calls itself, and the process is called recursion.

Recursion is a process where a function calls itself. It is used to solve a problem by breaking it down into smaller and smaller parts. The function calls itself until it reaches the base case.

Here is an example to find the Fibonacci series in python using recursion.

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

# print the first 10 Fibonacci numbers
for i in range(10):
    print(fibonacci(i), end="  ")

Output:

0 1 1 2 3 5 8 13 21 34

Lambda Function

Lambda functions are inline functions. lambda is a keyword used to create a lambda function.

Lambda function contains a single expression that is evaluated and returned.

# regular function
def hello():
    return "Hello"

# lambda function
hello = lambda: "Hello"

# call lambda function by using the variable
print(hello())

Lambda function can take arguments too. The argument is separated by a comma.

# argument in lambda function
sum = lambda a, b: a + b

# call lambda function
print(sum(1, 2))

Lambda functions can be passed as arguments to other functions.

chars = ["L", "c", "M", "D", "f", "y"]

# sort the list in ascending order
chars.sort(key=lambda x: x.lower())

# print the sorted list
print(chars)

Output:

['c', 'D', 'f', 'L', 'M', 'y']

Conclusion

This is the end of the Python Functions section. You have learned how to create functions in Python, how to use them, and how to return values from functions.

Additionally, you have learned how to use lambda functions, and how to pass them as arguments to other functions.