SlideShare a Scribd company logo
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

More Related Content

Similar to Unit 1-Part-5-Functions and Set Operations.pdf (20)

PPTX
Python Functions.pptx
AnuragBharti27
 
PPTX
Lecture 08.pptx
Mohammad Hassan
 
PPTX
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
PPTX
Python for Data Science function third module ppt.pptx
bmit1
 
PDF
functions- best.pdf
MikialeTesfamariam
 
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
PPTX
functions.pptx
KavithaChekuri3
 
PDF
Python Function.pdf
NehaSpillai1
 
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
PPTX
Functions in python, types of functions in python
SherinRappai
 
PPTX
Functions in Python Programming Language
BeulahS2
 
PPTX
Chapter 2 Python Functions
11210208
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Functions_new.pptx
Yagna15
 
PPTX
2 Functions2.pptx
RohitYadav830391
 
PDF
Functions2.pdf
prasnt1
 
PPTX
Functions in python programming and its calling statement
rehna9
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PPTX
Functions in Python with all type of arguments
riazahamed37
 
Python Functions.pptx
AnuragBharti27
 
Lecture 08.pptx
Mohammad Hassan
 
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Python for Data Science function third module ppt.pptx
bmit1
 
functions- best.pdf
MikialeTesfamariam
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
functions.pptx
KavithaChekuri3
 
Python Function.pdf
NehaSpillai1
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Functions in python, types of functions in python
SherinRappai
 
Functions in Python Programming Language
BeulahS2
 
Chapter 2 Python Functions
11210208
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Functions_new.pptx
Yagna15
 
2 Functions2.pptx
RohitYadav830391
 
Functions2.pdf
prasnt1
 
Functions in python programming and its calling statement
rehna9
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
Functions in Python with all type of arguments
riazahamed37
 

More from Harsha Patil (20)

PDF
Unit 5-Introduction of GUI Programming-Part2.pdf
Harsha Patil
 
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
PDF
Unit 6-Introduction of Python Libraries.pdf
Harsha Patil
 
PDF
Unit 5-Introduction of GUI Programming-Part1.pdf
Harsha Patil
 
PDF
Unit-2 Introduction of Modules and Packages.pdf
Harsha Patil
 
PDF
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
PDF
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
Harsha Patil
 
PDF
Unit 1-Part-1-Introduction to Python.pdf
Harsha Patil
 
PDF
Unit 1-Part-3 - String Manipulation.pdf
Harsha Patil
 
PDF
Unit 1- Part-2-Control and Loop Statements.pdf
Harsha Patil
 
PPTX
Introduction to Reinforcement Learning.pptx
Harsha Patil
 
PPTX
Introduction to Association Rules.pptx
Harsha Patil
 
PPTX
Introduction to Clustering . pptx
Harsha Patil
 
PPTX
Introduction to Classification . pptx
Harsha Patil
 
PPTX
Introduction to Regression . pptx
Harsha Patil
 
PPTX
Intro of Machine Learning Models .pptx
Harsha Patil
 
PPTX
Introduction to Machine Learning.pptx
Harsha Patil
 
PPTX
Unit-V-Introduction to Data Mining.pptx
Harsha Patil
 
PPTX
Unit-IV-Introduction to Data Warehousing .pptx
Harsha Patil
 
PPTX
Unit-III-AI Search Techniques and solution's
Harsha Patil
 
Unit 5-Introduction of GUI Programming-Part2.pdf
Harsha Patil
 
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
Unit 6-Introduction of Python Libraries.pdf
Harsha Patil
 
Unit 5-Introduction of GUI Programming-Part1.pdf
Harsha Patil
 
Unit-2 Introduction of Modules and Packages.pdf
Harsha Patil
 
Unit 4-Exception Handling in Python.pdf
Harsha Patil
 
Unit 1-Part-4-Lists, tuples and dictionaries.pdf
Harsha Patil
 
Unit 1-Part-1-Introduction to Python.pdf
Harsha Patil
 
Unit 1-Part-3 - String Manipulation.pdf
Harsha Patil
 
Unit 1- Part-2-Control and Loop Statements.pdf
Harsha Patil
 
Introduction to Reinforcement Learning.pptx
Harsha Patil
 
Introduction to Association Rules.pptx
Harsha Patil
 
Introduction to Clustering . pptx
Harsha Patil
 
Introduction to Classification . pptx
Harsha Patil
 
Introduction to Regression . pptx
Harsha Patil
 
Intro of Machine Learning Models .pptx
Harsha Patil
 
Introduction to Machine Learning.pptx
Harsha Patil
 
Unit-V-Introduction to Data Mining.pptx
Harsha Patil
 
Unit-IV-Introduction to Data Warehousing .pptx
Harsha Patil
 
Unit-III-AI Search Techniques and solution's
Harsha Patil
 
Ad

Recently uploaded (20)

PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Dimensions of Societal Planning in Commonism
StefanMz
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
Ad

Unit 1-Part-5-Functions and Set Operations.pdf

  • 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