0% found this document useful (0 votes)
9 views35 pages

Function 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views35 pages

Function 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Praveen Kumar A

Flow of Execution
Let’s observe how a function call works
3
1. The function is defined so that the 1
Python interpreter sees it.
2. When we want to add 2 numbers:
we call add2nums, and pass in the 2
arguments or input data (5 and 9, 4
for example) .
2
3. Execution jumps to the function 5
block, and the input data are stored
in the parameters num1 and num2
of add2nums.
4. The code of add2nums runs, producing a sum (14, for example). At the
end of add2nums, the sum is returned or sent back to the caller line of
code.
5. In these examples, the returned value is not assigned to a variable, so the
shell prints it to screen.
#program to add two numbers through a function
# add.py
def add2sum( x , y ):
s= x + y
return s
num1 = int(input("Enter first number :"))
num2 = int(input("Enter second number :"))
sum = add2sum(num1,num2)
print("sum of two given numbers is :", sum)
Number indicating next statement to be executed

__main__(add.py) 2
num1 = int(input("Enter first number :")) 1
num2 = int(input("Enter second number :")) It tells the currently
executing statement
sum = add2sum(num1,num2)
Python Console
print("sum of two given numbers is :",sum)

Data : >>>Enter first number : 3


num1 = 3

This is datapart of Statement 1


__main__ executed on console
Number indicating next statement to be executed

__main__(add.py) 3
It tells the currently
num1 = int(input("Enter first number :"))
executing statement
num2 = int(input("Enter second number :")) 2
sum = add2sum(num1,num2)
Python Console
print("sum of two given numbers is :",sum)
>>>Enter first number : 3
Data : >>>Enter second number : 7
num1 = 3
num2 = 7

This is Statement 2
datapart of executed on console
__main__
Number indicating next statement to be executed

__main__(add.py) 4
It tells the currently
num1 = int(input("Enter first number :"))
executing statement
num2 = int(input("Enter second number :"))
sum = add2sum(num1,num2) 3
print("sum of two given numbers is :",sum) Python Console
Data :
>>>Enter first number : 3
num1 = 3 >>>Enter second number : 7
num2 = 7

This is
datapart of
__main__
add2sum( 3 ,7 )
Statement 3 is a function call statement , hence add2sum
execution frame is created.
The values from _main_ are passed to it.

add2sum(x ,y)
Function add2sum() receives
the values in variables x any y s= x + y
def add2sum( x , y ) : return s
Now the statements of
add2sum()’s body will be Data :
executed x =3
y =7
add2sum(x ,y) 2 Statement 1 of
s= x + y function body
executed in memory
1
return s Internal Memory

Data : x = 3 3 + 7 = 10
y =7 s = 10
Value of s is given back to
add2sum(x ,y) _main_
s= x + y
return s 2 With last statement
of function body ,
Data : x = 3 control returns to
y =7 s = 10 the point wherefrom
the function was
called
Number indicating next statement to be executed

__main__(add.py) 4
num1 = int(input("Enter first number :")) It tells the currently
executing statement
num2 = int(input("Enter second number :"))
sum = add2sum(num1,num2)
print("sum of two given numbers is :",sum)
Data : Value of s is given back
num1 = 3 to _main_ , which
num2 = 7 sum = 10 stores it to variable
sum, This completes
the execution of
statement 3 of _main_
Number indicating next statement to be executed

__main__(add.py)
num1 = int(input("Enter first number :"))
num2 = int(input("Enter second number :")) It tells the currently
executing statement
sum = add2sum(num1,num2)
print("sum of two given numbers is :",sum) 4
Data :
num1 = 3
num2 = 7 sum = 10
Python Console
sum of two given number is 10
Calling / Invoking / Using a Function
(i) Passing literal as argument in function call
add2sum( 4, 5)
(ii) Passing variable as argument in function call
num1 = 10
num2 = 14
add2sum( num1, num2)
(iii) Taking input and passing the input as argument in function call
num1 = int(input(“Enter first number:”))
add2sum(num1, num2)
(iv) Using function call inside another statement
` print(add2sum(2 , 14))
(v)Using function call inside expression
z = add2sum(2 , 3) * 2
Function IO (1 of 2)
• A function can accept 0 or more input arguments, and it can
return 0 or 1 value.
• We have seen that the function add2sum has 2 input
arguments and 1 return value.
• Example of a function that has no input argument and no
return value:

• Example of a function that has 1 input argument and no return


value:

Praveen Kumar A
Function IO (2 of 2)
• Example of a function that has no input argument and 1 return
value
If x value is 5
Then output is
?

If x value is 2
Then output is
?

If x value is
4
Then What
is the
output ?
Returning Values from functions
Non-void functions
return < value >

The value being returned can be one of the following:


* a literal * a variable * an expression
For example, following are some legal return statements:
return 6+4 # expression involving literals being returned
return a**3 # expression involving variables and literals,
being returned
return (a + 8**2)/b

add_result = sum(a,b) # The returned valued being used in


assignment statement
print(sum(3,4)) # The returned valued being used in print statement
sum(4,5) > 6 # The returned valued being used in a relational expr
The return statement ends a function execution even if it is in the
middle of the function.
A function ends the moment it reaches a return statement or all
statements in function-body have been executed, whichever
occurs earlier
e.g., following function will never reach print() statement as return
is reached before that.

def check (a):

a = math.fabs(a)
This statement is unreachable
return a because check() function will end
with return and control will never
print(a) reach this statement

check(-15)
Void Functions

def greet():
void function but no
print(“hello”)
return statement

def greet():
print(“hello”)
return
void function with a
return statement
Returning Multiples Values

return <value1/variable1/expression1>,<value2/variable2/expression2>

def squared (x, y, z) :


return x *x, y*y, z*z

t = squared( 2 , 3, 4 ) Tuple t will be printed as


print(t) (4 , 9, 16)

def squared (x, y, z) :


return x *x, y*y, z*z

v1, v2, v3 = squared( 2 , 3, 4 )


The returned values are as under
print(v1, v2, v3) 4 9 16
Function arguments
Types of formal arguments are
• Required / Positional Arguments
the arguments must be provided for all parameters
(Required)
the values of arguments are matched with parameters,
position (Order) wise (Positional)
• Default Arguments
• Keyword (Named) Arguments

You can write any argument in any order


provided you name the arguments
Using Multiple Argument Types Together
Rules for combining all three types of arguments
Python states that in a function call statement

• an argument list must first contain positional (required) arguments


followed by any keyword argument.

• keyword arguments should be taken from the required arguments


preferably.

• you cannot specify a value for an argument more than once.


Predict the output of the following code fragment?

def check(n1=1, n2=2): def CALLME(n1=1,n2=2):


n1=n1+n2 n1=n1*n2
n2+=1 n2+=2
print(n1,n2) print(n1,n2)
check() CALLME()
check(2,1) CALLME(2,1)
check(3) CALLME(n2=3)
def sum(a,b,c):
return a+5, b+4, c+7
S will store the
S=sum(2,3,4) returned values as a
print(S) tuple

def sum(a,b,c):
storing the return a+5, b+4, c+7
values separately
s1, s2, s3=sum(2, 3, 4)
print(s1, s2, s3)

Praveen Kumar A
Why Use Functions (1 of 2)
• From this example we can
see that if we invest the
effort one time to define a
function, we can then call it
many times.
• This is because a function
always behaves the same
way, but given different
input data, it will produce a
different output.
• This make a function very adaptable. We can use add2nums any
time we need to add 2 numbers, without having to re-type the
code to add the numbers. This is the concept of re-usability in
programming.
Why Use Functions ( of 2)2
• A good example of re-usability is the print function. Someone
wrote the print function at one time, and the rest of us can
keep using print without having to write code to work with
the screen to print data.
• Functions also allow us to take a large project and divide it
into small logical blocks or functions. This concept is called
modularization.
• Modularization makes it easier to manage a large project
because if we need to change a part of the project, we can
simply replace some of the functions in the project. We don’t
have to take apart the whole project.
• Modularization also makes it easier to arrive at the complete
solution to a large problem by solving one small part at a
time.
__name__ variable is a special implicit variable that contains a string, and
the value of the string depends on how the code is being executed.

Basically there are two ways in which python interpreters execute code
and __name__ value is populated by this.

1. The most common way is to execute the file as a python script

In this case __name__ will contain the string “__main__”

2. By importing the necessary code from one python file to another file.

In this case __name__ will contain the imported module name

__name__ variable helps to check if the python file is being run directly or
if it has been imported from some other file.
Praveen Kumar A

You might also like