Ch3-Functions
Introduction
Function is a subprogram that acts on data and
often returns a value.
Large program into small units called functions.
Easier
No of lines are less
More readable/understandable
Understanding Functions
2
for x=1, result is 2
for x=2, result is 8
for x=3, result is 18
for x=4, result is 32
F(x)=2
Notataion f(x) is termed as function,
Where x is the argument.
Can have arguments
Can perform functionality
Can return some value.
Name of the function
Argument of the function
def calc(x):
r=2*x**2 Statement to return computed
body
result
retrun r
a=int(input(“enter a number”))
print(cal(a))
Function call
Calling/invoking /using a function
1.Passing literal as argument in function call.
cube(4)
2.Passing variable as argument in function call.
num=10
cube(num)
3.Taking input and passing the input as argument.
num=int(input(“enter a number”))
cube(num)
4.Using function call inside another stmt.
print(cube(3))
5.Using function call inside expression.
doubleofcube=2*cube(6)
Python function types
Built-in functions
int(), type(), len(), input()
Functions defined in modules
math module – sin(), random
module
User defined functions
programmer defines the function. Add(),
sub() cube()
Defining functions in python
keyword
def greet():
print(“good mrng”)
parameters
def sum(x,y):
s=x+y Function header
return s
Sample code 1 Sample code 3
def sumof3multiples1(n): def sumof3multiples1(n):
s=n*1+n*2+n*3 s=n*1+n*2+n*3
return s print(s)
Sample code 2
def areaofsquare(a):
return a*a
Sample code 3
def quote():
print(“Do not expect anything from anyone”)
Structure of a python program
By default, python names the segment with top-level statements
(main program) as __main__
def function():
:
def function2():
:
#top level stmt
stmt 1
stmt2
def greet():
print(“hi there”)
print(“at the top-level”)
print(“inside”,__name__)
Flow of execution in a function call
Flow of execution refers to the order in which statements are executed
during a program run.
A execution frame contains:
Some internal information (used for debugging)
Name of the function
Values passed to function
Variables created within function
Information about the next instruction to be executed.
1 # function with two arguments
2 def add_numbers(num1, num2):
3 sum = num1 + num2
4 print("Sum: ",sum)
5 # function call with two values
6 add_numbers(5, 4)
Execution always begins at the first line
Comment lines are not executed
Ifits is function header, executes only the header line
for any error
Stmt inside the function is not executed.
Function can have another function in it
Without calling outer function, inner function can’t be
called.
When function is called, first function header is
executed.
Function ends with return or without return
1. #program for functions
2. def calcsum(x,y):
3. s=x+y
4. return s
5.
6.num1=float(input(“enter first number:”))
7.num2=float(input(“enter second number:”))
8.sum=calcsum(num1,num2)
9.print(“sum of two given numbers is”,sum)
2,6,7,8,2,3,4,8,9
Arguments and parameters
Arguments : python refers to the values being passed as arguments
sum(5,6) (Actual parameter / actual argument)
Parameters: Values being received as parameters
def sum(x,y) (formal parameter / formal argument)
Arguments can be a , literals, variables and expressions
Error
def one(a+1,b)
c=a+b
retrun(c)
Today’s Program:(04.03.23)
1.Write a function that takes amount-in-dollars-to-rupee conversion
price, it then returns the amount converted to rupees. Create the
function in both void and non-void forms.
2. Write a function to calculate volume of a box with appropriate default
values for its parameters. Your function should have the following input
parameters.
(a)Length of box
(b)Width of box
(c)height of box
Passing Parameters
Positional arguments (required arguments)
Default arguments
Keyword (or named ) arguments
Positional arguments (required arguments)
def check(a,b,c) #function header
check (x,y,z)
Function call
check(2,x,y)
check(2,5,7)
Default arguments
def interest (principal,time,rate=0.10): #function header
Si_int=interest(5400,2) Function call
Si-int=interest(6100,3,0.15)
def Legal
interest(prin,time,rate=0.10):
Illegal
def interest(prin,time=2,rate):
def interest (prin=2000,time=2,rate): Illegal
def interest(prin,time=2,rate=0.10): Legal
def legal
interest(prin=200,time=2,rate=0.10):
Keyword (or named ) arguments
def interest(prin,time,rate) #function header
interest (prin=2000,time=2,rate=0.10)
interest(time=4,prin=2600,rate=0.90) Function call
interest(time=2,rate=0.12,prin=2000)
Using Multiple argument types together
Function call
interest(5000,time=5)
Rules:
Positional should be in first and then keyword argument.
Cannot specify a value foe an argument more than one
time.
def interest(prin,cc,time=2,rate=0.09):
retrun prin*time*rate
Function call
interest(prin=3000,cc=5) Legal
interest(rate=0.12,prin=5000,cc=4) Legal
interest(cc=4,rate=0.12.prin=5000) Legal
interest(5000,3,rate=0.05) Legal
interest(rate=0.05,5000,3) Illegal
interest(5000,prin=300,cc=2) Illegal
interest(5000,principal=300,cc=2) Illegal
interest(500,time=2,rate=0.05) illegal
Returning values from functions
Functions returning some values (non void functions)
Functions not returning any value (void functions)
Functions returning some values (non void functions)
Literal
A variable
Expression
return 5
return 6=4
return a
return a**3
return (a+8**2)/b
return a+b/c
add_result=sum(a,b)
print(sum(3,4))
sum(4,5)>6
If the returned value is not used, no error
def check(a):
a=math.fabs(a)
retrun a
print(a)
check(-15)
Function not returning any value
Code 1:
def replicate(): @@@@
None
print(“@@@@”)
print(“replicate())
Code 2:
def replicate(): @@@@
return “@@@@”
print(“replicate())
Returning Multiple values
def square(x,y,z):
return x*x,y*y,z*z
t=square(2,3,4)
Print(t) #t is tuple
def square(x,y,z):
return x*x,y*y,z*z
a,b,c=square(2,3,4)
Print(a,b,c) #a,b,c normal variables created based
on the values
Scope of variables
Parts of program within which a name is legal and
accessible , is called scope of the name.
For example: Local scope
Ticket 1 –monument1
Ticket 2-monument 2 Global scope
Ticket 3-for the all monuments in the city
Global scope
All the variables in the__main__ program are called
as global scope and can be used inside the whole
program (in other functions and blocks)
Local scope
A local variable is a variable defined within a function.
example
1.def calcsum(x,y):
2. z=x+y
3. return z
4.num1=int(input(“enter first number:”))
5.num2=int(input(“enter second number:”))
6.sum=calsum(num1,num2)
7.print(“sum of given number is”,sum)
x,y,z are local scope variables
num1, num2,sum are global scope variables
Variable defined outside all functions
are global variables
x=5
def func(a):
b=a+1
retrun b
y=int(input(“enter number’))
z=y+func(x)
print(z)
Example 2
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.num1=int(input(“enter first number:”))
8.num2=int(input(“enter second number:”))
9. num3=int(input(“enter third number:”))
10.print(“average is”,average(num1,num2,num3))
Lifetime of a variable
Thetime for which a variable of name remains in
memory is called lifetime of variable
Global variable-program run time
Local variable-particular function run time
Name resolution (resolving scope of a Name)
LEGB
L- Local Environment
E- Enclosing Environment
G- Global Environment
B- Built-in Environment
Case 1: variable in global but not in local
def calcsum(x,y):
s=x+y
print(num1)
return s
num1=int(input(“enter first number:”))
num2=int(input(“enter second number:”))
print(“sum is”,calcsum(num1,num2))
Case 2: variable neither in local and
global
def greet()
print(“hello”,name)
greet()
error
Case 3:Same variable in local and global
def state():
tigers=15
print(tigers)
Output:
tigers=95 95
Print (tigers) 15
State() 95
Print(tigers)
What if you want the global variable
inside local scope
Global keyword is used
def state():
global tigers
tigers=15 Output:
print(tigers) 95
tigers=95 15
Print(tigers) 15
State()
Print(tigers)
Find output
def update(x=10):
x+=15
print(‘x=‘,x) Output:
x=20 x=25
update() x=20
print(‘x=‘,x)
Find the output
def addem(x,y,z):
print(x,y,z)
def prod(x,y,z): Output:
return x*y*z 6 16 26
a=addem(6,16,26) None 36
b=prod(2,3,6)
Print(a,b)
Write a function that takes a positive
integer and returns the one’s position
digit of the integer.
Mutable /Immutable Properties of
passed data objects
Sample code 1 Calling myFunc1() by passing ‘num’ with value 3
Inside myFunc1()
Passing an Immutable type value to a function.
Value received in ‘a’ as 3
1.def myfunc1(a): Value of ‘a’ now changes to 8
returning from myFunc1()
2. print(“\t Inside myFunc1()”) Back from myFunc1().Value of ‘num’ is 3
3. print(“\t Value received in ‘a’ as”,a)
4. a=a+2
5. print(“\t value of ‘a’ now changes to”,a)
6. print(“\t returning from myfunc1()”)
7.num=3
8.print(“calling myFunc1() by passing ‘num’ with value”,num)
9.myfunc1(num)
10.print(“Back from myFunc1().Value of ‘num’ is”,num)
Sample code 2
Passing an mutable type value to a function-making changes in place
1.def myfunc2(myList): List before function call:[1]
Inside called function now
2. print(“\t Inside Called function now”) List received:[1]
3. print(“\t List received:”,myList) List within called function, after changes:
[3]
4. myList[0]+=2 List after function call:[3]
5. print(“\t List within called function,after
changes:”,myList)
6. return
7.List1=[1]
8.print(“List before function call:”,List1)
9.myFunc2(List1)
10.print(“\n List after function call:”,List1)
Sample code 3
Passing an mutable type value to a function – Adding/Deleting items to it
1.def myfunc3(myList): List before function call:[1]
Inside called function now
2. print(“\t Inside Called function now”)
List received:[1]
3. print(“\t List received:”,myList) List after adding some elements:[1,2,5,1]
List within called function, after all changes:
4. myList.append(2) [1,2,1]
5. myList.extend([5,1]) List after function call:[1,2,1]
6. print(“\t List after adding some elements”,myList)
7. myList.remove(5)
8. print(“List within called function.after all changes:”,myList)
9. return
10.List1=[1]
11.print(“List before function call:”,List1)
12.myFunc3(List1)
Sample code 4
Passing an mutable type value to a function – Assigning parameter to a new value/variable.
1.def myfunc4(myList):
2. print(“\n Inside Called function now”)
List before function call:[1,4]
inside called function now
3. print(“\t List received:”,myList) List received: [1,4]
4. new=[3,5] List within called function, after changes: [3,5
List after function call:[1,4]
5. myList=new
6. myList.append(6)
7. print(“\t List within called function,after changes”,myList)
8. return
9.List1=[1,4]
10.print(“List before function call:”,List1)
11.myFunc4(List1)
12.print(“\n List after function call:”,List1)
Mutable Argument (say A) assigned to mutable parameter (say p)
If p is not assigned any new name If p is assigned a new name or different
or different data type value datatype value (e.g p=different-variable,
changes in p are performed in then any changes in p are not reflected
place and get reflected back to back to __main__
__main__ that is , A will show the That is , A will not show changed data.
changed data.
That means, we can sat that:
Changes in immutable types are not reflected in the caller function at all.
Changes, if any, in mutable types
Are reflected in caller function if its name is not assigned a different
variable or datatype.
Are not reflected in the caller function if it is assigned a different variable
or datatype.