Functions - 1

Definition: A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Here are simple rules to define a function in Python:

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.

  • The code block within every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller.

  • A return statement with no arguments is the same as return None.

SYNTAX :

def functionname( parameters ):
    "function_docstring"
    function_suite
    return [expression]

Example -1:

def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return 

printme("Python") #calling

Output: Python

Calling a Function :

  1. Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

  2. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.

Example -2:

#Function definition is here
def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return;
    
#Now calling printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Output

I'm first call to user defined function!

Again second call to the same function

Pass by Reference vs Pass by Value:

Let's understand this concept in C++ programming

Example-3:

#include <iostream>
using namespace std;

void func(int *x)
{
cout << "In func x=" << *x << " address of x=" << x <<  endl;

*x=4;
return;
}

void func1(int x){
cout << "In func1 x=" << x << " address of x=" << &x <<  endl;
x=5;
cout << x << endl;
return;
}

int main() {
// your code goes here
int x = 3;
func(&x);  //pass by reference in c++
cout << "In main after func x=" << x << " address of x=" << &x << endl;

func1(x);  //pass by value in c++
cout << "In main after func1 x=" << x << " address of x=" << &x << endl;
return 0;
}

Output:

All parameters (arguments) in the Python language are passed by reference.

  • If you change what a parameter refers to within a function, the change also reflects back in the calling function if the address is same like in some cases of list and dictionary (when complete list is not changed as shown in below example)

Example-4:

def ref_demo(x):
    x[1] = 4
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))

Output:

x= [12, 3, 6] id= 2689911761288

Within Function: x= [12, 4, 6] id= 2689911761288

Outside Function: x= [12, 4, 6] id= 2689911761288

  • If you change what a parameter refers to within a function, the change doesn't reflects back in the calling function if the address is different like in case of number, string, tuple, and some cases of list and dictionary

Example-5 (A):

def ref_demo(x):
    x = [1,5,2]
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))

x= [12, 3, 6] id= 2689911760072

Within Function: x= [1, 5, 2] id= 2689911760584

Outside Function: x= [12, 3, 6] id= 2689911760072

Example-5 (B):

def ref_demo(x):
    x[0] = 1
    x[1] = 11
    x[2] = 111
    print("Within Function: x=",x," id=",id(x))
    
x = [12,3,6]
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))

x= [12, 3, 6] id= 2480079932808

Within Function: x= [1, 11, 111] id= 2480079932808

Outside Function: x= [1, 11, 111] id= 2480079932808

Example-6:

def ref_demo(x):
    x = 8
    print("Within Function: x=",x," id=",id(x))
    
x = 7
print("x=",x," id=",id(x))
ref_demo(x)

print("Outside Function: x=",x," id=",id(x))

x= 7 id= 140707894174288

Within Function: x= 8 id= 140707894174320

Outside Function: x= 7 id= 140707894174288

Example 7 :

#!/usr/bin/python3
#Function definition is here
def changeme( mylist ): 
    "This changes a passed list into this function"
    print("Values inside the function before change: ", mylist)
    mylist[2]=50
    print("Values inside the function after change: ", mylist)
    return

#Now you can call changeme function
mylist = [10,20,30]
changeme(mylist)
print("Values outside the function: ", mylist)

Output: Values inside the function before change: [10, 20, 30]

Values inside the function after change: [10, 20, 50]

Values outside the function: [10, 20, 50]

Example 8 :

#!/usr/bin/python3
#Function definition is here
def changeme( mylist ):
    "This changes a passed list into this function"
    mylist = [1,2,3,4] # This would assi new reference in mylist
    print ("Values inside the function: ", mylist)
    return
#Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)

Output: Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]

Function Arguments:

You can call a function by using the following types of formal arguments −

  1. Required arguments

  2. Keyword arguments

  3. Default arguments

  4. Variable-length arguments

  1. Required Arguments :-

Required arguments are the arguments passed to a function in correct positional order.

The number of arguments in the function call should match exactly with the function definition.

Example 9 :

#!/usr/bin/python3
#Function definition is here
def printme( str ):
    "This prints a passed string into this function"
    print (str)
    return
#Now you can call printme function
printme("Python")

Output: Python

2. Keyword arguments

Keyword arguments are related to the function calls.

When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

Example 10 :

#Function definition
def printme( str ):
    "This prints a passed string into this function"
    print(str)
    return;

#calling printme function
printme( str = "Python is Awesome")

Output: Python is Awesome

3. Default arguments:

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Example 11 :

#!/usr/bin/python3
#Function definition is here
def printinfo( name, age = 35 ):
    "This prints a passed info into this function"
    print("Name: ", name)
    print("Age ", age)
    return
#Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )

Output:

Name: miki

Age 50

Name: miki

Age 35

4. Variable-length arguments:

You may need to process a function for more arguments than you specified while defining the function.

These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Values passed

Example 12 :

#Function definition
def printinfo( arg1, *vartuple ):
    "This prints a variable passed arguments"
    print("Output is: ")
    print(arg1)
    print(type(vartuple))
    print(vartuple)
    for var in vartuple:
        print(var)
        print(type(var))
    return;

#Calling Function
printinfo(10)
printinfo(3,754,75)
x = [2,4,3]
y = [12,4,3]
z = [45,65]
printinfo(x,y,z)

Output is:

10

<class 'tuple'>

()

Output is:

3

<class 'tuple'>

(754, 75)

754

<class 'int'>

75

<class 'int'>

Output is:

[2, 4, 3]

<class 'tuple'>

([12, 4, 3], [45, 65])

[12, 4, 3]

<class 'list'>

[45, 65]

<class 'list'>

When using (*) symbol while passing more than one argument, values are passed as tuple

Example-13:

#Function definition
def printinfo( arg1, *abc ):
    "This prints a variable passed arguments"
    print("Output is: ")
    print(arg1)
    print(type(abc))
    for var in abc:
        print(var)
    return;

#Calling Function
printinfo("mikki")
printinfo(70, 60, 50)

Output:

Output is: mikki

<class 'tuple'>

Output is:

70

60

50

Last updated