1. Python 3-Functions
• 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.
• Python gives us many built-in functions like print(), etc.
• We can also create own functions.
• These functions are called user-defined functions.
1
2. Python 3-Functions
Defining a Function
• You can define functions to provide the required functionality.
• There 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.
2
3. Python 3-Functions
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
Example
def printstr(str):
"This prints a passed string into this function"
print (str)
return
3
4. Python 3-Functions
Calling a Function
• Defining a function gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
• 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.
# 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("This is first call to the user defined function!")
printme("Again second call to the same function")
4
5. Python 3-Functions
• Pass by Reference vs Value
• 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.
• Example-
# 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]
5
6. Python 3-Functions
Pass by Reference vs Value
Example 2:
# 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]
6
7. Python 3-Functions
Function Arguments
You can call a function by using the following types of formal arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
7
8. Python 3-Functions
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.
• To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error -
# 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()
Output:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme()
TypeError: printme() missing 1 required positional
argument: 'str' 8
9. Python 3-Functions
Keyword Arguments
• Keyword arguments are related to the function calls.
• When you use keyword arguments in a function call, the caller identifies the arguments by
the parameter name.
• This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
• You can also make keyword calls to the printme() function in the following ways-
Example1:
# 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( str = "My string")
Output:
My string
9
10. Python 3-Functions
Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age: ", age)
return
# Now you can call printinfo function
printinfo( age=15, name=“Omkar" )
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=15, name=“Omkar" )
printinfo( name=“Omkar" )
Output:
Name: Omkar
Age: 15
10
11. Python 3-Functions
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.
• The following example gives an idea on default arguments, it prints default age if it is not
passed.
Example1:
# Function definition is here
def printinfo( name, age = 25 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=15, name=“Omkar" )
printinfo( name=“Omkar" )
Output:
Name: Omkar
Age 15
Name: Omkar
Age 25
11
12. Python 3-Functions
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.
Syntax for a function with non-keyword variable arguments is given below
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments.
This tuple remains empty if no additional arguments are specified during the function call.
12
13. Python 3-Functions
Variable-length Arguments-Example
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo(10)
printinfo(70, 60, 50)
Output is:
10
Output is:
70
60
50
13
14. Python 3-Functions
• The Anonymous Functions
• These functions are called anonymous because they are not declared in the standard
manner by using the def keyword.
• You can use the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one value in the form of
an expression.
• They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an
expression.
• Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
• Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation by
passing function, during invocation for performance reasons.
14
15. Python 3-Functions
Syntax
The syntax of lambda function contains only a single statement, which is as follows
lambda [arg1 [,arg2,.....argn]]:expression
Example
#!/usr/bin/python3
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
Output:
Value of total : 30
Value of total : 40
15
16. Python 3-Functions
The return Statement
• 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.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total )
Output:
Inside the function : 30
Outside the function : 30
16
17. Python 3-Functions
Recursion
• Python also accepts function recursion, which means a defined function can call itself.
• Recursion is a common mathematical and programming concept.
• It means that a function calls itself.
• This has the benefit of meaning that you can loop through data to reach a result.
• The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power.
• However, when written correctly, recursion can be a very efficient and mathematically-
elegant approach to programming.
17
18. Python 3-Functions
Recursion Example
def try_recursion(k):
if(k > 0):
result = k + try_recursion(k - 1)
print(result)
else:
result = 0
return result
print("nnRecursion Example Results")
try_recursion(6)
Output:
Recursion Example Results
1
3
6
10
15
21
18
19. Python 3-Functions
Scope of Variables
• All variables in a program may not be accessible at all locations in that program.
• This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can access a
particular identifier.
• There are two basic scopes of variables in Python-
• Global variables
• Local variables
19
20. Python 3-Functions
• Namespaces and Scoping
• Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).
• A Python statement can access variables in a local namespace and in the global
namespace.
• If a local and a global variable have the same name, the local variable shadows the
global variable.
• Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
• Python makes educated guesses on whether variables are local or global. It assumes
that any variable assigned a value in a function is local.
20
21. Python 3-Functions
• Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
• The statement global VarName tells Python that VarName is a global variable. Python
stops searching the local namespace for the variable.
Global vs. Local variables
• Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
• Local variables can be accessed only inside the function in which they are declared.
• Global variables can be accessed throughout the program body by all functions.
• When you call a function, the variables declared inside it are brought into scope.
21
22. Python 3-Functions
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
Output:
Inside the function local total : 30
Outside the function global total : 0
22
23. Python 3-Functions
• We define a variable Money in the global namespace.
• Within the function Money, we assign Money a value, therefore Python assumes Money as
a local variable.
• However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
• Example:
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)
23
24. Python 3-Functions
The globals() and locals() Functions
• The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.
• If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
• If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.
• The return type of both these functions is dictionary.
• Therefore, names can be extracted using the keys() function.
24
25. Python Set Operations
• The set in python can be defined as the unordered collection of various items enclosed
within the curly braces.
• The elements of the set can not be duplicate.
• The elements of the python set can not be changed.
• There is no index attached to the elements of the set, i.e., we cannot directly access any
element of the set by the index.
• We can print them all together or we can get the list of elements by looping through the
set.
25
26. Python Set Operations cont..
Creating a set:
• The set can be created by enclosing the comma separated items with the curly braces.
• Python also provides the set method which can be used to create the set by the passed
sequence. Creating set using curly brackets:
Creating set using curly brackets:
city={"Pune", "Mumbai", "Nashik"}
print(city) # {'Pune', 'Nashik', 'Mumbai'}
for i in city: print(i, end=“”) # Pune Nashik Mumbai
Creating set using set() method:
names=set([“Shubham”, “Nilesh”, “Pranav”])
print(names) #{'Pranav', 'Shubham', 'Nilesh'}
26
27. Python Set Operations cont..
Adding items to the set:
• Python provides the add() method which can be used to add some particular item to the
set.
names.add("Rajesh")
print(names) #{'Pranav', 'Shubham', 'Rajesh', 'Nilesh'}
• To add more than one item in the set, Python provides the update() method.
print(city) #{'Pune', 'Nashik', 'Mumbai'}
city.update(["Jalgaon","Nagpur","Satara"])
print(city) # {'Satara', 'Jalgaon', 'Pune', 'Mumbai', 'Nagpur', 'Nashik'}
27
28. Python Set Operations cont..
Python provides discard() method which can be used to remove the items from the set.
city.discard("Mumbai")
print(city) # {'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
Python also provide the remove() method to remove the items from the set.
print(city) #{'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
city.remove("Satara")
print(city) #{'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
We can also use the pop() method to remove the item.
However, this method will always remove the first item.
print(city) #{'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
city.pop() #'Jalgaon‘
28
29. Python Set Operations cont..
Python provides the clear() method to remove all the items from the set.
print(city) #{'Nashik', 'Dhule'}
city.clear()
print(city) #set()
Difference between discard() and remove():
If the item to be deleted from the set using discard() doesn't exist in the set, the python will
not give the error.
If the item to be deleted from the set using remove() doesn't exist in the set, the python will
give the error.
29
30. Python Set Operations cont..
Union of two Sets:
The union of two sets are calculated by using the or (|) operator.
The union of the two sets contains the all the items that are present in both the sets.
Ex.
s1={1,2,3}; s2={3,4,5}
s3=s1|s2
print(s3) #{1,2,3,4,5}
Python also provides the union() method which can also be used to calculate the union of
two sets.
print(s1.union(s2)) #{1,2,3,4,5}
30
31. Python Set Operations cont..
Intersection of two sets:
• The & (intersection) operator is used to calculate the intersection of the two sets in
python.
• The intersection of the two sets are given as the set of the elements that common in both
sets.
Ex
s1={"Pune","Mumbai","Jalgaon"}
s2={"Nashik","Pune","Nagpur","Jalgaon"}
s3=s1&s2
print(s3) #{'Jalgaon', 'Pune'}
• Using intersection() method
s3=s1.intersection(s2)
print(s3) #{'Jalgaon', 'Pune’}
31
32. Python Set Operations cont..
The intersection_update() method:
• The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).
• The Intersection_update() method is different from intersection() method since it modifies
the original set by removing the unwanted items.
• On the other hand, intersection() method returns a new set.
Example:
a={1,2,3,4,5}
b={3,5,7,8,9}
a.intersection_update(b)
print(a) #{3, 5}
32
33. Python Set Operations cont..
Difference of two sets:
The difference of two sets can be calculated by using the subtraction (-) operator.
The resulting set consists of all the elements form set 1 which are not available in set2
Example
a={1,2,3,4}
b={3,5,4,8}
c=a-b
print(c) #{1, 2}
print(b-a) #{5,8}
Using difference() method
print(a.difference(b)) #{1,2}
33
34. Python Set Operations cont..
The difference_update():
The set difference_update() method modifies the existing set.
If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed,
then B gets modified into ( B – A).
Ex. a={1,2,3,4,5}
b={3,4,5,6}
a.difference_update(b)
print(a) #{1,2}
The symmetric_difference():
This in-built function of Python Set helps us to get the symmetric difference between two
sets, which is equal to the elements present in either of the two sets, but not common to both
the sets.
print(a.symmetirc_difference(b)) #{1,2,6}
34
35. Python Set Operations cont..
The symmetric_difference_update method:
symmetric_difference() method returns a new set which contains symmetric difference of
two sets.
The symmetric_difference_update() method updates the set calling
symmetric_difference_update() with the symmetric difference of sets.
a={1,2,3,4}
b={2,3,6,7}
a.symmetric_difference_update(b)
print(a) #{1,4,6,7}
35
36. Python Set Operations cont..
issuperset() in Python:
The issuperset() method returns True if all elements of a set A occupies set B which is
passed as an argument and returns false if all elements of B not present in A.
This means if A is a superset of B then it returns true; else False.
Syntax: A.issuperset(B) checks whether A is a superset of B or not.
True if A is a superset of B; otherwise false.
Example:
A={1,2,3,4,5}; B={2,3,4}
A.issuperset(B) #True
B.issuperset(A) #False
issubset() in python: returns true if first set is a subset of seconds set otherwise false
A.issubset(B) #False
B.issubset(A) #True
36
37. Python Set Operations cont..
issubset() in python:
returns true if first set is a subset of seconds set otherwise false
A.issubset(B) #False
B.issubset(A) #True
isdisjoint() function in Python:
Two sets are said to be disjoint when their intersection is null.
In simple words they do not have any common element in between them.
Syntax: seta.isdisjoint(setb)
a={1,2,3}; b={3,4,5}; c={7,8,9}
a.isdisjoint(b) #False
a.isdisjoint(c) #True
37
38. Python Set Operations cont..
Set comparisons:
• Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by
using which we can check whether a set is subset, superset, or equivalent to other set.
• The boolean True or False is returned depending upon the items present inside the sets.
Example
a={1,2,3,4}; b={1,2,3}; c={1,2,3};
print(a>b) #True
print(a<b) #False
print(b>a) #False
print(a==b) #False
print(b==c) #True
print(a>=b) #True
38
39. Summary
• Functions provide better modularity for your application and a high degree of code
reusing.
• User defined function along with it’s syntax discussed in detail.
• All parameters (arguments) in the Python language are passed by reference.
• Different types of arguments regarding function are discussed in detail with examples.
• The lambda keyword is used to create small anonymous functions.
• Python also accepts function recursion, which means a defined function can call itself.
• Local and Global scope of variables are discussed in detail with examples.
• Set operations are discussed in detail with examples.
39