Functions in Python

FREE Online Courses: Your Passport to Excellence - Start Now

You might have encountered a lot of functions like print(), etc. till now. These are built-in functions, whose properties are pre-defined.

What if you want to create your own function, the properties of which you decide? In this article, you will learn functions, defining a function, different types of functions, etc.

Introduction to Functions in Python

A function is a block of statements that work together under the same name. A function might or might not take an input/ inputs. The same thing applies to the outputs. There are some functions that return value(s) and there are ones that do not.

Functions can be classified into the following three types:
1. Built-in functions: These are functions that are already predefined in Python like print(), min(), etc.
2. User-defined functions: These are the functions that programmers create and use at the places where they need them.
3. Anonymous functions: These are the functions that do not have a name and are defined by the user. These are also called lambda functions.

Python Built-in Functions

As said before, built-in functions are functions whose purpose is preset and defined in Python. While some need importing of the required module, some do not. And these can be used from any part of the program. Examples of such functions are print(), int(), str(), all(), sum(), sqrt(), etc.

Python User-defined Functions

Besides the built-in functions, Python allows the programmers to create their own function and decide its operation. These are called user-defined functions. These provide the following advantages:

1. This helps us organize and divide the function, especially if the program is very long.
2. This also makes it easier to modify and debug the code.
3. It prevents rewriting the same piece of code, as we can call the function from any part of the program.

Defining a Function in python

We can define a function using the ‘def’ keyword. The syntax of a function is

def func_name(args):
    statement(s)

From the above syntax we can see that:

1. The definition starts with the ‘def’ keyword.
2. After this, the function name is written followed by a pair of parentheses and the colon (:).
3. We can pass the arguments inside the parentheses, separated by commas if there is more than one argument.
4. The statement(s) form the body of the function.
5. One important and common thing to note here is the indentation. Every line of the body should be indented with four spaces/ a tab. The lines indented are only considered as the pens under the function.
6. We can also add an optional return statement, which will give the desired value (if any) when the function is called.

An example of a simple function that prints a statement is shown below.

Example of a function:

def welcome(name):
    print("Hello, ",name,"Welcome to PythonGeeks!")

1. Naming a function in Python

We know that the functions we define have a name, there are some exception which we will discuss later in this article. Like we have rules for naming a variable, we have them for the functions too. The names of the user-defined functions also come under the identifiers. The rules are as follows.
a. It should start with either a letter (a-z, A-z) or an underscore ( _).
b. It must contain only alphabets (a-z, A-z), numbers(0-9), and an underscore.
c. The name must not be a Python keyword.
It is suggested to name it according to its functionality.

2. Empty Functions in Python

Empty functions are not allowed in Python. We cannot define a function without writing at least one line of code. We get an error by running an empty function. A solution for it is to use the ‘pass’ statement. This can be considered as a function that does nothing.

Example of an empty function:

def empty_func():
    pass

When we call this function we get no output.

3. Reassigning

We can reassign a function by defining it again using the same name. We can also change the arguments and the lines of code, but the name should be the same. Remember that the Python programming language is case-sensitive.

Calling a function in Python

One of the important steps in using a function is to call the function. Only when a function is called, the lines of code under it get executed. We can all the functions using the function name followed by the parentheses.

We can pass the arguments, if any, within the parentheses. For example, when we call the above function, we get the following output.

Example of calling a function:

welcome('abc')

welcome('Python')

Output:

Hello, abc Welcome to PythonGeeks!

Hello, Python Welcome to PythonGeeks!

DocString in Python

The document string, called docstring, in short, is the first string written right after the function header. It is like a comment that describes what the function is used for. Though it can be of a single-line statement, generally it is preferred to write in multiple lines enclosed by triple quotes.

Example of a docstring:

def welcome(name):
   '''This function
takes the name as input and
welcomes the person
'''
    print("Hello, ",name,"Welcome to PythonGeeks!")

This docstring gets stored as a __dic__ attribute of a function. We can use the same to get a function’s docstring as shown in the below example:

Example of getting a function’s docstring:

print("The docstring of the welcome function is: ")
print(welcome.__doc__)

print("The type of the docstring is ",type(welcome.__doc__))

Output:

The docstring of the welcome function is:
This function
takes the name as input and
welcomes the person
The type of the docstring is <class ‘str’>

If we define a function with no docstring and if we try to get its docstring, then we get no output.

Example of getting a docstring of a function with no docstring:

def fun():
    print("This is a function")

print(fun.__doc__)

We do not get any output here.

Python Function Arguments

As we saw above that we can give inputs to the functions. Arguments are the values passed to a function when we call it.

There are many situations where the word parameters and the word arguments are used interchangeably. It is important to know the difference between them. Arguments are the inputs supplied to the function while using it. Whereas parameters are the names used inside the function while defining it. The arguments are mapped to the respective parameters.

Example of showing the difference between parameters and arguments:

def add(num1,num2):
    sum=num1+num2
    print(sum)

  
a=4
b=5

add(a,b)

Output:

9

In the above example, the variables ‘a’ and ‘b’ are the arguments. And ‘num1’ and ‘num2’ are the parameters. Here ‘a’ is mapped to ‘num1’ and ‘b’ to ‘num2’ on calling the function.

This example also shows how we define a function that takes inputs and also calls the function by passing the arguments. We can call the function again by passing values of different data types as shown below.

Example of passing arguments to a function:

add(0.9,3)

add('Python','Geeks')

Output:

3.9

PythonGeeks

But we cannot pass those values as arguments on which the function cannot do the required operations. For example, we cannot add a string and a number. Because of this, we get an error on passing the wrong values as shown below.

Example of passing arguments to a function:

add('tres',54)

Output:

Traceback (most recent call last):
File “<pyshell#59>”, line 1, in <module>
add(‘tres’,54)
File “<pyshell#52>”, line 2, in add
sum=num1+num2
TypeError: can only concatenate str (not “int”) to str

types of arguments in python

The arguments given to a function are of four types in Python:

1. Required Argument:

Required arguments are the arguments passed to a function in a certain order. When we call the function we need to pass the same number of arguments mentioned in the function definition.

Example of a required argument:

def greatest(n1,n2,n3):
    if(n1>n2 and n1>n3):
        print(n1," is the greatest of the three numbers")
    elif(n2>n1 and n2>n3):
        print(n2," is the greatest of the three numbers")
    else:
        print(n3," is the greatest of the three numbers")


greatest(5,2,9)

greatest(1,6)

greatest(2,9,5)

Output:

9 is the greatest of the three numbers

Traceback (most recent call last):
File “<pyshell#91>”, line 1, in <module>
greatest(1,6)
TypeError: greatest() missing 1 required positional argument: ‘n3’

9 is the greatest of the three numbers

The function has 3 parameters. When we pass 3 arguments while calling the function, 5 is mapped to n1, 2 to n2, and 9 to n3. We can see that when we passed only 2 arguments we got an error. This is because we did not pass enough arguments. We get an error if we pass extra arguments also.

In this case, it might not give any difference in switching the values of the three numbers. But there are cases where the switching of the values might give an error or unexpected results. For example,

Example of required arguments:

def division(num,den):
    print(num/den)

division(4,2)

division(2,4)

division(0,5)

division(5,0)

Output:

2.00.5

0.0

Traceback (most recent call last):
File “<pyshell#82>”, line 1, in <module>
division(5,0)
File “<pyshell#78>”, line 2, in division
print(num/den)
ZeroDivisionError: division by zero

We can see that on changing the values, we got different output in the second call and an error in the fourth call of the function.

2. Keyword Arguments

When we are concerned about the order of the values passed, we can use the keyword arguments to the function. In this case, when we call a function by equating values to the respective parameter names used while defining a function. Here even if we switch the variables, but it will not be a problem as we use the names.

Example of keywords arguments:

def give_section(std,section):
    print("The section of the student ",std,"is ",section)

give_section(std='Ram',section='A')

give_section(section='A',std='Ram')

Output:

The section of the student Ram is A

The section of the student Ram is A

3. Default Arguments:

Default arguments solve the problem of the number of arguments passed to the function. We can give a default value to the parameters while defining the function. It is compulsory that all the parameters in the function should be assigned a default value. We are allowed to give the default values to only some of the parameters.

But the no required arguments should be mentioned after the default ones. That is, all the required arguments should be preceding the default ones.

If we do not pass the argument for that parameter, it uses the default value assigned during the definition. Or else, the given argument will be used.

Example of default arguments:

def avg_mark(sub1,sub2,sub3,sub4=0,sub5=0):
    avg=(sub1+sub2+sub3+sub4+sub5)/5
    print("The average of the marks in the 5 subjects is ",avg)

avg_mark(63,78,96,84,87)

avg_mark(45,34,65,53)

Output:

The average of the marks in the 5 subjects is 81.6

The average of the marks in the 5 subjects is 39.4

4. Variable number of arguments

When we do not know the number of arguments to be passed to the function, we can choose the option of variable arguments.

These parameters and arguments are of variable length and the parameters are not named separately in the function. All these are named under the same name which is preceded by an asterisk(*) in the function header.

Example of variable length arguments:

def values_of_list(*varList):
    for i in varList:
        print(i)

    
values_of_list(3,4)

values_of_list('a',6,9.0,'y')

Output:

3
4
a
6
9.0
y

We can set the other types of arguments along with the variable ones too as shown below:

Example of required and variable-length arguments:

def langs(name,*listLangs):
    print("The languages ", name," can speak are:")
    for lan in listLangs:
        print(lan)

langs('abc','English')

langs('xyz','English','Italian','French')

Output:

The languages abc can speak are:
English
The languages xyz can speak are:
English
Italian
French

Here the names ‘abc’ and ‘xyz’ are mapped to the name in their calls. And the other arguments are mapped to the ‘listLangs’ parameter.

Python Functions With Return Statement

Functions can not only take the inputs but can also return outputs. We can use the ‘return’ keyword followed by the variable that is to be outputted.

Example of a function that returns a value:

def pow(a,b):
    return a**b

var=pow(4,3)
print(var)

Output:

64

When the pow() function is called, the value it returns gets stored in the variable ‘var’. This is the reason when we try to print the value of the variable, we get the output as 64.

When a return statement has reached the execution of the function stops. Even if there are lines after the function, those do not get executed. This property is used when we want the respective output based on the condition satisfied.

Example of a function that returns a value:

def sign(n):
    if(n>0):
        return 'positive'
    if(n<0):
        return 'negative'
    return 'zero'

sign(5)

sign(-19)

sign(0)

Output:

‘positive’

‘negative’

‘zero’

Here if the first condition (n>0) is satisfied, then the return statement is executed and none of the other lines after this will not run. If the second condition is True, then the return statement under that if block executes and the control comes out of that function. If none of the conditions are satisfied, then the last return executes returning zero.

Scope of the Variable in Python

The scope of a variable is the region of the program where the variable is accessible. A variable cannot be accessed from everywhere in the program. Its scope depends on the region where it is created. And the time for which the variable exists is called its lifetime.

Based on this we can mainly have two types of scopes:

1. Python Local Scope:

This is the scope of the variable created inside a function. This variable can be accessed only inside that function as it exists only when the function is executing. If we try to use it outside the function, we get an error.

Example of the variable with local scope:

def func():
    var=10
    print("Inside the function, the value of var is ",var)

func()

print("Outside the function, the value of var is:",var)

Output:

Inside the function, the value of var is 10
Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
print(“Outside the function, the value of var is:”,var)
NameError: name ‘var’ is not defined

We can see that we could print the value of ‘var’ inside the function. But globally we got an error.

2. Python Global Scope:

These are variables that can be accessed from any part of the program. These exist throughout the execution of the code.

Example of the variable with global scope:

name="Python"

def func():
    print("Inside the function, the value of name is:",name)

print("Outside the function, the value of name is:",name)

func()

Output:

Outside the function, the value of name is: Python
Inside the function, the value of name is: Python

But the changes done on the global variable inside the function do not get reflected globally. This is because a new variable gets created when we assign a new value to the variable. An example is shown below.

Example of local changes not getting reflected globally:

num=5.6

def func():
    num=4.3
    print("Inside the function, the value of num is:",num)
print("Before executing the function")
print("num=",num)

func()

print("After executing the function")
print("num=",num)

Output:

Before executing the function
num= 5.6
Inside the function, the value of num is: 4.3
After executing the function
num= 5.6

To solve this problem we can use the ‘global’ keyword while changing the value inside the function.

Example of using the ‘global’ keyword:

num=4

def func():
    global num
    num=9
    print("Inside the function, the value of num is:",num)
print("Before executing the function")
print("num=",num)

func()

print("After executing the function")
print("num=",num)

Output:

Before executing the function
num= 4
Inside the function, the value of num is: 9
After executing the function
num= 9

Deleting the Functions in Python

We can use the ‘del’ keyword followed by the function name to delete a function in Python. We cannot call the function after deleting it. Because it does not exist anymore, we get an error.

Example of deleting a function:

def fun():
    print("Hello!")

fun()

del fun

print("After deleting the function")

fun()

Output:

Hello!

After deleting the function

Traceback (most recent call last):
File “<pyshell#33>”, line 1, in <module>
fun()
NameError: name ‘fun’ is not defined

Pass by Reference and Pass by Value

All the arguments in Python are passed by reference. This means that rather than just the value of the variable, we pass the address of the variable as an input to function. This is the reason when we modify the variable inside the function, the value gets reflected globally.

Example of pass by reference:

list1=['a','b','c']
def add(list_1):
    list_1.append('d')
    print("Inside the function,list_1 =",list_1)

print("Before calling the function")
list1

add(list1)

print("After calling the function")
list1

Output:

Before calling the function
[‘a’, ‘b’, ‘c’]
Inside the function,list_1 = [‘a’, ‘b’, ‘c’, ‘d’]
After calling the function
[‘a’, ‘b’, ‘c’, ‘d’]

But however, if we reassign the value, then the changes do not show globally because a new variable gets created.

Example of pass by reference:

list1=['a','b','c']
def add(list_1):
    list_1=[1,2,3]
    print("Inside the function,list_1 =",list_1)

print("Before calling the function")
list1

add(list1)

print("After calling the function")
list1

Output:

Before calling the function
[‘a’, ‘b’, ‘c’]
Inside the function,list_1 = [1, 2, 3]
After calling the function
[‘a’, ‘b’, ‘c’]

Lambda Functions in Python

Lambda functions are the third type of function. These are also called anonymous functions. These are defined using the keyword ‘lambda’ rather than the ‘def’ keyword. The properties of lambda functions are:

1. These can take any number of arguments but can return only one value.

2. Because it requires an expression, it cannot be directly called in a print statement.

3. Like any other function, these have their own namespace.

The syntax to create a lambda function is:

lambda arguments: expression

Example of lambda function:

prod=lambda a,b:a*b

prod(3,9)

prod([1,2,3],3)

Output:

27

[1, 2, 3, 1, 2, 3, 1, 2, 3]

The functions filter(), map() and reduce()

The lambda functions are mostly used with the functions filter(), map() and reduce(). An example of using these functions is shown below.

Example of lambda function with filter(), map() and reduce():

list1=[1,3,5,6,2,8]

list2=list(map(lambda i:i**2,list1)) #squaring each value of the list
list2

list3=list(filter(lambda i:i%2==1,list1)) #storing only the odd values
list3

from functools import reduce

list4=reduce(lambda x,y: x if x>y else y,list1) #finding the maximum of the list
list4

Output:

[1, 9, 25, 36, 4, 64]

[1, 3, 5]

8

Recursion in Python

Recursion is the process of calling the same function inside the body of the function. Wondering how will we stop execution if the function keeps calling itself?

We use a condition in the function that needs to be satisfied to call itself again. This condition is also called the base condition. The variable on which the condition depends keeps changing to reach the base case. The below example shows how to print the sum of ‘n’ natural numbers.

Example of recursion:

def sum(n):
    if(n==0):
        return 0
    return n+sum(n-1)

sum(5)

Output:

15

When we call the function the condition n==0, the base condition, is checked. Since it is False, the second return statement executes.

This gives 5+sum(4). And sum(4) returns 4+sum(3). Then sum(3) returns 3+sum(2).The output of sum(2) is 2+sum(1). And sum(1) will return 1+sum(0). The sum(0) satisfies the base condition so it returns 0. And the final result will be 5+4+3+2+1+0=15.

Interview Questions on Functions in Python

Q1. Write a function to check if that gives the remainder on dividing the largest value by the other one.
Ans 1. Below is the example of a function that does the given operation:

def rem(n1,n2):
    if(n1>n2):
        return n1%n2
    return n2%n1

rem(5,9)

Output:

4

Q2. Write a function that takes the input of a variable number of letters and returns the list of all the letters present in the word ‘PythonGeeks’.

Ans. Below is the example of a function with variable number of arguments:

def list_of_letters(*letters):
    list1=[]
    for l in letters:
        if l in 'PythonGeeks':
            list1.append(l)
    return list1

list_of_letters('r','y','o','k','e')

Output:

[‘y’, ‘o’, ‘k’, ‘e’]

Q3. Write a function to return the factorial of a given number using recursion.
Ans 3. Below is the example of a function finding the factorial:

def fact(n):
    if(n==1):
        return 1
    return n*fact(n-1)

fact(6)

Output:

720

Q4. Write a lambda function to calculate the intersection of two sets using the lambda function.
Ans 4. We can use the filter() function with the condition that the element of the first set is in the second one.

Example of a finding intersection of two sets using lambda function:

set1={1,2,3,4}
set2={4,5,6,2}
set3=set(filter(lambda i:i in set2,set1))
set3

Output:

{2, 4}

Q5. Write a function to check if a string is a palindrome or not using recursion.
Ans 5. We can check if a function is a palindrome or not by checking if the ‘i’ th letter from the first is equal to that from the last.

Example of checking palindrome using recursion:

def pal(string):
    if(not(len(string))):
        return True
    if(string[0]!=string[len(string)-1]):
        return False
    return pal(string[1:-1])

pal('abccba')

Output:

True

Python Quiz on Functions

Conclusion

In this article, we learned functions, their types, different properties of functions, etc. We also learned about recursion, one of the important concepts to be known.

And at the end, we saw some coding questions. Hope this article helped you in knowing the topic of the functions in Python. Happy learning!

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *