Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
It is difficult to manage a single list of instructions. Thus large program are broken down into smaller units known as functions. Functions can be invoked from other parts of the program. it make program more readable and understandable making program easy to manage.
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Python functions
1.
2. Working with Functions
Function is a subprogram that acts on data and often returns a
value.
●Advantages of Function
1.Program development made easy and fast
2.Program testing becomes easy- corrections need to be made only at one place
3.Code sharing becomes possible
4.Code re-usability increases
5.Increases program readability
●Python Function Types
1. Built-in functions-> predefined, always available ( len(),type(),input() )
2. Function defined in modules-> predefined in particular module, need to
import modules. ( ceil() in math, randint() from random)
3. User defined functions-> defined by programmer.
3. Structure of User Defined Functions
Function Header # name of function and its parameters
Parameters # variables that are listed within the parentheses of function header
Function Body # block of statements indented.
Indentation # All statements within same block have same indentation.
(usually 4 spaces in the beginning of statement)
Non-void Function
Void Function
1. def sumofmultiples(n): OR def
sumofmultiples(n):
s=n*1 + n*2 + n*3
s=n*1 + n*2 + n*3 return s
4. Creating & Calling a Function (user defined)
argument:- values being passed are actual arguments (appears in function call)
Parameters:- values being received as parameters are formal (appears in function header)
A function is defined using the def keyword in python.E.g. program is given below.
1. def my_own_function(d): #Function header
2. print("Hello from a function")
#Function Body
return d # Function may/maynot
have return statement
3. print("hello before calling a function") #main function/ high level
4. r=my_own_function(4) #function call
5. print("hello after calling a function")
Flow of execution of program:
5. 1. #Python Program to add two number through function
2. def add2number2(x, y): # here x, y are parameters
3. r=x+y
4. return r
5.
6. # take input from the user
7. num1 = int(input("Enter first number: "))
8. num2 = int(input("Enter second number: "))
9. Result=add2numbers(num1, num2) # here num1, num2 are Arguments
10. print("The sum. of", num1,"and", num2,"is",Result)
1. # Python Program to find the factorial of a given number
2. def factorial(n): # parameters=
3. fact = 1 # local variable=fact
4. for i in range(1,n+1):
5. fact = fact * i
6. return fact
7. print ("The factorial of 5 is : ",end="")
8. print (factorial(5)) #arguments=
6.
7.
8.
9. Python Supports three types of formal parameters
1. Positional parameters (Required parameters)
2. Default parameters appears
in Function Header
3. Arbitrary parameters/ Variable length parameters
4. Named parameters (Keyword parameters)
appears in Function Call
1. def check(a,b,c):
2. s=a+b+c
3. print(s)
11. Arbitrary arguments / Variable-length Arguments
Sometimes you may need more arguments to process function then you mentioned in the definition(when you are passing . If we don’t know in advance
about the arguments needed in function, we can use variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition which can hold non-keyword variable-length arguments and
a double asterisk (**) is placed before a parameter in function which can hold keyword variable-length arguments.
If we use one asterisk (*) like *var, then all the positional arguments from that point till the end are collected as a tuple called ‘var’ and
if we use two asterisks (**) before a variable like **var, then all the positional arguments from that point till the end are collected as a dictionary called
‘var’.
def greet(*args):
# This function greets all the person in the names tuple.
# names is a tuple with arguments
for n in args:
print("Hello", n)
#Calling the function
greet("Monica", "Luke", "Steve", "John")
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
def display(*args, **kwargs):
"""This function display all persons in names tuple.
and all keyword arguments as dictionary"""
for items in args:
print (items)
for items in kwargs.items():
print (items)
#Calling the function
display(‘John','Mary','Nina',Mohan='LA',Seema='NY',
Reena='DC‘)
12. Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using global keyword.
3. Non local variable – accessible in nesting of functions, using nonlocal keyword. Used in nested functions.
14. Non Local Variable Program
1.def myfunc1():
2. x = "John"
3. def myfunc2():
4. global x
5. x = "hello"
6. myfunc2()
7. return x
8.X=“SEEMA”
9.print(myfunc1())
1.def myfunc1():
2. x = "John"
3. def myfunc2():
4. nonlocal x
5. x = "hello"
6. myfunc2()
7. return x
8.
9.print(myfunc1())
Global Environment
For main()
X->SEEMA
Local Environment
For myfunc1()
X -> “Hello”
LOCAL ENV FOR
MYFUNC2()
x-=“hello”
16. Possible combinations of Returning values from functions
1. non-void functions without arguments
2. non-void functions with some arguments
3. void functions without arguments
4. void functions with some arguments
Returning multiple values from funtion
1. def squared(x,y,z) :
return x*x, y*y, z*z
t=squared(1,2,3) # t is tuple
a,b,c=t
print(t)
2. def squared(x,y,z) :
return x*x, y*y, z*z
a,b,c=squared(1,2,3) # unpack received tuple in a,b,c
t= (a,b,c)
print(t)
1
4
9
17. Write Flow of Execution of program (trace the program).
Draw the entire environment, for all variables at the time line 10 is being executed.
Predict the output of the program
1. def calcSum(a,b,c):
2. s=a+b+c
3. return s
4. def average( x,y,z):
5. sm=calcSum(x,y,z)
6. return sm / 3
7. n1=int(input(“Number 1:”))
8. n2=int(input(“Number 2:”))
9. n3=int(input(“Number 3:”))
10.print(“Average of these number is”, average(n1,n2,n3))
Flow of execution of program:
1-4-7-8-9-10-4-5-1-2-3-5-6-10
Global Environment
n1 -> 11
n2 -> 22
n3 -> 33
22.0
Local Environment
For average()
X -> 11
Y -> 22
Z -> 33
Sm -> 66
66/3 -> 22.0
Local Environment for
calcSum()
A -> 11
B -> 22
C-> 33
S -> 66
Lifetime of Variable
Local Variable Global Variable
It is a variable which is declared within
a function or within a block.
It is a variable which is declared outside
all the functions.
It is accessible only within a
function/block in which it is declared.
It is accessible throughout the program.
18.
19. Passing Immutable Type value to a Function
1. def func1( x):
2. print(“Inside functions my value is :”,x)
3. x=x ** 2
4. print(“Now my value is : “, x)
5. n=3
6. print(“Calling func1() by passing ‘n’ with value :”, n)
7. func1(n)
8. print(“Back from func1(). Now value of ‘n’ is :, n )
# Draw environments and predict the outputs
Conclusion-
Changes in immutable type are not reflected in the
caller function at all.
Output-
Calling func1() by passing ‘n’ with value
:3
Inside functions my value is :3
Now my value is : 9
20. Conclusion-
Changes in mutable types are reflected in caller function if its name is not
assigned a different variable or datatype
1. def func1(Rlist):
2. print(“Inside function”)
3. print(“Received List: “, Rlist)
4. Rlist[0] += 5
5. print( “List within called function
after change: “,Rlist)
6. Slist=[25]
7. print(“List before function call:”,Slist)
8. func1(Slist)
9. print(“List after function call :”, Slist)
Rlist Rlist[0]
Rlist
Rlist[0]
Slist Slist[0]
25
25 +5
21. Passing Mutable Type value to a function ( making changes in place)
1. def func1(Rlist) :
2. print(“Inside Function”)
3. print(“Received List :”,Rlist)
4. Rlist.append(100)
5. Rlist.extend ( [ 11,13,17] )
6. print(“List after adding some elements:”,
Rlist)
7. Rlist.remove(13)
8. print(“List after removing one element:”,
Rlist)
9. Slist=[25]
10.print(“List before function call : “,Slist)
11.func1(Slist)
12.print(“List after function call : “,Slist)
Rlist / Rlist[0]
OR Slist/ Slist[0]
Rlist
Rlist
Rlist
Slist / Slist[0]
Conclusion-
Changes in mutable types are reflected in caller function if it is not assigned a different variable or datatype
25 100 11 13 17
25 100
25 100 11 17
22. Passing Mutable Type value to a function ( making changes in place)
1. def func1(Rlist) :
2. print(“Inside Function”)
3. print(“Received List :”,Rlist)
4. Newlist=[1,2,3]
5. Rlist=Newlist
6. Rlist.append(100)
7. Rlist.extend ( [ 11,13,17] )
8. print(“List after adding some elements:”, Rlist)
9. Rlist.remove(13)
10. print(“List after removing one element:”, Rlist)
11. Slist=[25]
12. print(“List before function call : “,Slist)
13. func1(Slist)
14. print(“List after function call : “,Slist)
Rlist / Rlist[0]
Newlist =[1,2,3]
Rlist =Newlist
Rlist .append(100)
Rlist.extend([11,13,17])
Rlist
Rlist.remove(13)
Slist / Slist[0]
Conclusion-
Changes in mutable types are not reflected in caller function if it is assigned a different variable or datatype within
function definition
1 2 3
1 2 3
1 2 3 100
1 2 3 100 11 13 17
1 2 3 100 11 17
23. Resolving scope of a Name (LEGB rule)
The LEGB rule is a kind of name lookup procedure, which determines the order in which Python looks up names.
Python scopes are implemented as dictionaries that map names to objects. These dictionaries are commonly called namespaces. These
are the concrete mechanisms that Python uses to store names. They’re stored in a special attribute called __dict__.
(import math and show how to check variables in a module like math.__dict__)
L – Local Environment / Namespace- inside function
E – Enclosing Environment / Namespace -inside nested functions nonlocal scope
G - Global Environment / Namespace- inside main/module scope
B - Built-in Environment / Namespace - from anywhere in program
(keywords, built in functions and
attributes)
Otherwise Python would report error.
B G E L
24. Lambda Function
Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by
using lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of
expression.
Syntax:- lambda arguments : expression
Example
1.
x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluated and returned.
print("sum = ",x(20))
2.
x = lambda a,b:a+b
# a and b are the arguments and a+b is the expression which gets evaluated and returned.
print("sum = ",x(20,10))
3.
#the function table(n) prints the table of n
def table(n):
return lambda a:a*n; # a will contain the iteration variable i and a multiple of n is returned at each function call
n = int(input("Enter the number?"))
b = table(n) # the entered number is passed into the function table. b will contain a lambda function which
# is called again and again with the iteration variable i
for i in range(1,11):
print(n,"X",i,"=",b(i)) #the lambda function b is called with the iteration variable i,