Python Functions



Definition


Python functions can be defined as the block of code which can be called or used just by typing a name which is given by the programmer, during the writing of the program.

Python Functions are defined using the “def” keyword.


Syntax

def function_name(arguments):
    # block of code
    return expression

Types of Python Functions


  1. User-defined functions — These are those functions which are defined by the user or programmer.
  2. Built-In functions — These are those functions that are provided by the python i.e. pre-defined e.g. range(), print().

Here, we will discuss about User-defined functions.


Advantages of Python Functions


  • Rewriting — Python Functions reduces rewriting of code again and again as we can use the code inside a function just by calling that function.
  • Organizing — Python Functions helps us to organize a big program.
  • Reusability — We can use Python Functions any number of times in a program.

Creating a function


Steps

  1. Write “def“.
  2. Write function name with space.
  3. Write parenthesis ().
  4. Write colon :
  5. From the next line, start writing the code inside function after a valid indentation(4 white spaces).

def function_name():
    print("This is a simple function")

Calling a function

Example

def function_name():
    print("This is a simple function")
function_name()

Output

This is a simple function


The return statement


We use return statement to return some specific value or result at the end of a function.

The return statement can not be used outside a functon.

The return statement terminates the execution of the function and transfers the result where the function is called.


Example 1

def function_name():
    print("This is a simple function")
    return 2
a = function_name()
print(a)

Output

This is a simple function
2

Example 2

def function_name():
    # print("This is a simple function")
    return 2
function_name()
print(function_name())

Output

2

Example 3

def function_name():
    print("This is a simple function")
    return 2
function_name()
print(function_name())

Output

This is a simple function
This is a simple function
2

Example 4

def function_name():
    print("This is a simple function")
    return 2
print(function_name())
print(function_name)

Output

This is a simple function
2
<function function_name at 0x7ff839f1ce18>

You are free to return a string, list, tuple, or any expression like 2+3-5*3.


pass statement


We can use the “pass” statement if we want to define a function without any content inside it.

Generally, the pass statement is used when we want a function to be empty for some reason.


Example

def myfunction():
    pass
myfunction()

Output

Program outputs nothing


Arguments


Arguments are the information that we pass in a function. We need to pass information i.e. arguments externally.

Arguments are passed into a function inside parantheses.

We can pass any number of arguments by seperating them with comma(s).


Example 1

def myFun(arg):
    print("Passed argument is==>", arg)
myFun("I am a argument")

Output

Passed argument is==> I am a argument

Example 2

We need not to specify the type of arguments, and we can pass different types of arguments at a time.

def myFun(name, age, roll, likes):
    print("My name is", name)
    print("My age is", age)
    print("My roll no is", roll)
    print("I like", likes[0], "and", likes[1])
myFun("John", 22, 12, ["Music", "Dancing"])

Output

My name is John
My age is 22
My roll no is 12
I like Music and Dancing

Number of Arguments


We should pass the same number of arguments as the function needs i.e. if we have defined the function to take 3 arguments then we should call the function by passing 3 arguments(not less not more).


Example 1

def addThree(num1, num2, num3):
    return num1+num2+num3
addition = addThree(1, 2, 3)
print(addition)

Output

6

Example 2

def addThree(num1, num2, num3):
    return num1+num2+num3
addThree(1, 2)

Output

Traceback (most recent call last):
  File "f:/vscode/python/main.py", line 3, in <module>
    addThree(1, 2)
TypeError: addThree() missing 1 required positional argument: 'num3'

Example 3

def addThree(num1, num2, num3):
    return num1+num2+num3
addThree(1, 2, 3, 4)

Output

Traceback (most recent call last):
  File "f:/vscode/python/main.py", line 3, in <module>
    addThree(1, 2, 3, 4)
TypeError: addThree() takes 3 positional arguments but 4 were given


Parameters Vs Arguments


  • Parameters — When we define a function then the variable(s) inside the parentheses are called parameter(s).
  • Arguments — When we call a function then the value(s) we pass inside the parentheses are called the argument(s).

Types of arguments


  1. Required Arguments
  2. Default Arguments
  3. Variable-length Arguments
  4. Keyword Arguments

Required Arguments


The arguments which are fixed in number and position are the required arguments.

These are the arguments which should match their exact position during the calling of the function.

If either of the argument is not provided in the function call or does not match the position, the python interpreter will give you the error.


Example

def myFun(name, age, roll, likes):
    print("My name is", name)
    print("My age is", age)
    print("My roll no is", roll)
    print("I like", likes[0], "and", likes[1])
myFun("John", 22, 12, ["Music", "Dancing"])

Output

My name is John
My age is 22
My roll no is 12
I like Music and Dancing

Default Arguments


In python, we are allowed to initialize the arguments during the definition of the function i.e. when we are creating or defining a function.

If we do not pass the value of a default argument, then the value we initialize the default argument during the function definition will be automatically assigned to the default argument and the python interpreter will give no error.

We use assignment operator(=) to make default arguments.


Example

def myFun(name, roll, likes, age=32):
    print("Name:", name)
    print("Age:", age)
    print("Roll No:", roll)
    print("Likes:", likes[0], "and", likes[1])
myFun("John", 12, ["Music", "Dancing"])
print()
myFun("John", 12, ["Music", "Dancing"], 22)

Output

Name: John
Age 32
Roll No 12
Likes Music and Dancing

Name: John
Age 22
Roll No 12
Likes Music and Dancing

Variable-length Arguments


Sometimes, we may not know the number of arguments going to be passed in the function, in that case, we can use variable-length arguments.

Variable-length Arguments are defined using star(*) before the argument during the defining of the function. Usually, we use *args for this purpose.

The arguments we pass as Variable-length Arguments are treated as tuple.


Example 1


def addAll(*args):
    result = 0
    for x in args:
        result = result + x
    return result
print("Sum is", addAll(1, 2, 3, 4, 5))

Output

Sum is 15

Example 2


def addAll(*args):
    print(type(args))
    return sum(args)
print("Sum is", addAll(1, 2, 3, 4, 5))

Output

<class 'tuple'>
Sum is 15


Keyword Arguments


Python allows us to send arguments in key=value format.

During this type of arguments, the order of arguments does not matter.

Keyword’s name should match the argument’s name in the function definition. If matches found then the keyword values get copied to the arguments, else python interpreter will give the error.


Example 1

def addAll(val1, val2, val3):
    return val1+val2+val3
print(addAll(val1=4, val2=5, val3=6))

Output

15

Example 2

def addAll(val1, val2, val3):
    return val1+val2+val3
print(addAll(val1=4, val3=5, val2=6))

Output

15

Variable-length Keyword Arguments(**kwargs)


Python provides us the flexibility to pass Variable-length Keyword Arguments.

These are those keyword arguments that do not have fixed length i.e. during defining a function we do not know the number of keyword arguments are going to be passed.

These are represented using **kwargs. Unlike *args, which are treated as tuples, these are treated as a dictionary.


Example

def addAll(**kwargs):
    print(type(kwargs))
    print(kwargs)
    result = 0
    for x in kwargs:
        result = result + kwargs[x]
    print(result)
addAll(key1=1, key2=2, key3=3)

Output

<class 'dict'>
{'key1': 1, 'key2': 2, 'key3': 3}
6

Recursion


Simplest definition — Function calling function itself.

This is a logical and mathematical concept where we define a function to call itself to return the desired result. A recursive function should always have a termination condition.

If the function does not have a termination condition then the function will not terminate, so the programmer should always be careful while writing a recursive function.


Example 1

Finding factorial of a number Using Recursion

def factorial(n):
    if n==1:
        return n
    else:
        return factorial(n-1) * n
number = int(input("Enter a number:"))
if number<0:
    print("Enter a non-negative number")
else:
    print(factorial(number))

Output

Enter a number:5
120

Example 2

Finding sum of natural number Using Recursion

def naturalSum(n):
    if n==1:
        return n
    else:
        return naturalSum(n-1) + n
number = int(input("Enter a number:"))
if number<=0:
    print("Enter a natural number")
else:
    print(naturalSum(number))

Output

Enter a number:6
21