Skip to content
Related Articles

Related Articles

Improve Article
Functions in Python
  • Difficulty Level : Easy
  • Last Updated : 09 Feb, 2021

A function in Python is an aggregation of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can call the function to reuse code contained in it over and over again. 

Functions can be both built-in or user-defined. It helps the program to be concise, non-repetitive, and organized.

Syntax: 

def function_name(parameters):
    """docstring"""
    statement(s)

Example:

Python




# A simple Python function to check
# whether x is even or odd
 
 
def evenOdd(x):
    if (x % 2 == 0):
        print "even"
    else:
        print "odd"
 
 
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Output



even
odd

Docstring

The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice.

The below syntax can be used to print out the docstring of a function:

Syntax: print(function_name.__doc__)

Example:

Python3




def say_Hi():
    "Hello! geeks!"
 
 
print(say_Hi.__doc__)

Output:

Hello! geeks!

The return statement

The return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller.

Syntax: return [expression_list]

The return statement can consist of a variable, an expression, or a constant which is returned to the end of the function execution. If none of the above is present with the return statement a None object is returned.

Example:

Python3




def square_value(num):
    """This function returns the square
    value of the entered number"""
    return num**2
 
 
print(square_value(2))
 
print(square_value(-4))

Output:



4
16

Pass by Reference or pass by value? 

One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. Parameter passing in Python is the same as reference passing in Java.

Example:

Python




# Here x is a new reference to same list lst
def myFun(x):
    x[0] = 20
 
 
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something else, the connection between the passed and received parameter is broken. For example, consider the below program.
 

Python




def myFun(x):
 
    # After below line link of x with previous
    # object gets broken. A new object is assigned
    # to x.
    x = [20, 30, 40]
 
 
# Driver Code (Note that lst is not modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output
[10, 11, 12, 13, 14, 15]

Another example to demonstrate that the reference link is broken if we assign a new value (inside the function). 

Python




def myFun(x):
 
    # After below line link of x with previous
    # object gets broken. A new object is assigned
    # to x.
    x = 20
 
 
# Driver Code (Note that lst is not modified
# after function call.
x = 10
myFun(x)
print(x)
Output
10

Exercise: Try to guess the output of the following code. 

Python




def swap(x, y):
    temp = x
    x = y
    y = temp
 
 
# Driver code
x = 2
y = 3
swap(x, y)
print(x)
print(y)
Output
2
3

Default arguments: 

A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument. The following example illustrates Default arguments. 
 



Python




# Python program to demonstrate
# default arguments
 
 
def myFun(x, y=50):
    print("x: ", x)
    print("y: ", y)
 
 
# Driver code (We call myFun() with only
# argument)
myFun(10)
Output
('x: ', 10)
('y: ', 50)

Like C++ default arguments, any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.

Keyword arguments: 

The idea is to allow the caller to specify the argument name with values so that caller does not need to remember the order of parameters.

Python




# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
    print(firstname, lastname)
 
 
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output
('Geeks', 'Practice')
('Geeks', 'Practice')

Variable-length arguments:

We can have both normal and keyword variable number of arguments. Please see this for details. 

Example 1: 

Python




# Python program to illustrate
# *args for variable number of arguments
 
 
def myFun(*argv):
    for arg in argv:
        print(arg)
 
 
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output
Hello
Welcome
to
GeeksforGeeks

Example 2:

Python3




# Python program to illustrate
# *kargs for variable number of keyword arguments
 
 
def myFun(**kwargs):
    for key, value in kwargs.items():
        print("%s == %s" % (key, value))
 
 
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output
first == Geeks
mid == for
last == Geeks

Anonymous functions: 

In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. Please see this for details.

Python3




# Python code to illustrate the cube of a number
# using lambda function
 
 
def cube(x): return x*x*x
 
cube_v2 = lambda x : x*x*x
 
print(cube(7))
print(cube_v2(7))
Output
343

Quick Links : 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :