Understanding Functions in Python
Understanding Functions in Python
Function Introduction
Functions
Functions- Need, Advantages
Function types
Creating functions
Flow of execution
Arguments/parameters
Void and non void functions
Return values from functions
Function Introduction
What are functions ?
Advantages of functions
Function types
• Built – in functions are predefined functions
Eg. print() int(), input()
• Functions defined in modules
Can be used when module is imported .
Eg.
import math
[Link]()
• User defined functions (UDF)
We make our own functions
Eg Calculate(),Sum() etc
User defined functions
Two components needed to use functions in a program:
Function definition (body/block of function)
- consist of name of function,arguments/parameters
used, statements in the function.
Function call.(Invoking the function)
- the statement which executes the function
Syntax:
def functioname(argument/parameter list): #
statements in the function
Output
hello before calling a function
Hello from a function
hello after calling a function
Program to print sum of two numbers using
a function sum()
def sum(a,b):
c=a+b #function definition
print (c )
OUTPUT
X=10 40
Y=30 60
sum(X,Y) #function call.
sum(20,40) #function call.
Flow of execution
(order in which statements are executed)
def sum(a,b): 1. def sum(a,b):
c=a+b 2. c=a+b
print(c) 3. print (c )
X=10 4.X=10
Y=30 5.Y=30 OUTPUT
sum(X,Y) [Link](X,Y) 40
sum(20,40) [Link](20,40) 60
print("End") [Link](“Endʺ) End
Flow of execution
4->5->6->1->2-3->7->1-> 2- >3->8
Quiz
Consider the code below. Line 1 is called…
Quiz
What will the following Python program print out? (Given that each
word will actually print on a new line)
def fred():
print("Zap",end=" ")
A. Zap ABC jane fred jane
def jane(): B. Zap ABC Zap
print("ABC",end=" ") C. ABC Zap jane
D. ABC Zap ABC
jane() E. Zap Zap Zap
fred()
jane()
Quiz
What will the following Python program print out? (Given that each
word will actually print on a new line)
name = “Jane Eyre"
def myFunction(parameter):
A. value
value = "First" B. Second
value = parameter C. parameter
D. First
print(value) E. Jane Eyre
myFunction("Second")
Arguments / Parameters
Values listed along with function name in brackets are known as
arguments/parameters.
Arguments that are used in the function call are called actual
arguments Or actual parameters. Their values are sent to the
function. Actual arguments can be literal, variable or expression.
X=10 X=10
Y=30 Y=30
sum(X,Y) #function call P=sum(X,Y) #function call
print("Sum is ", P)
OUTPUT
OUTPUT
Sum is 40
Sum is 40
X=10 X=10
Y=30 Y=30
P=sum(X,Y) #function call print("Sum is ",sum(X,Y)) #function call
print("Sum is ", P)
OUTPUT
Sum is 40
Non Void functions without parameters(No formal parameters, with return value)
Non Void functions with parameters (With formal parameters, with return value)
Void and non void functions
# case1: Void functions without arguments # case 2: Void functions with arguments
OUTPUT
OUTPUT
SUM IS 40
SUM IS 40
# case 3: Non Void functions without arguments # case 4: Non Void functions with arguments
elif n==0:
print("Factorial is", 1)
else: Assignment :
p=1 Write a program to input a number. Pass this to a
function factorial which finds factorial of the number.
for i in range(1,n+1) : The function should return the factorial.
p= p*i
print("Factorial=",p)
num = int(input("Enter a number"))
factorial(num)
Program to input principal,rate and time . Find Simple
interest using a function.
Functions Part- 2
Returning None
#Return statement without a value will return the literal None.
def sum(a,b):
c=a+b OUTPUT
return None
X=10
Y=30
Z=sum(X,Y)
print(Z)
Non Void functions can return variable,
literal or expressions
def sum(a,b):
c=a+b
if c>30 :
def power(a):
return (1) # returning literal return a**2 # returning expressions
else:
return(0) # returning literal X=10
Y=power(X)
X=10 print(Y)
Y=30
Z=sum(X,Y)
print(Z) OUTPUT
100
OUTPUT
1
def power(a):
return a**2,a**3
X=10 OUTPUT
100 1000
Y,Z=power(X)
print(Y,Z)
def sum_of_squares(a,b,c):
Output:
p=Square(a)
Sum of squares=125
q=Square(b)
Square of 4=16
r=Square (c)
return p+q+r
X=10
Y=3
Z=-4
W=sum_of_squares(X,Y,Z)
print("Sum of squares=",W)
S=Square(4)
print("Square of 4=",S)
def outer(a):
def inner(Y):
Z=Y+11
return Z
b=inner(a)
print(b)
X=10
#inner(X) #NameError name inner is not defined
outer(X) # output 21
Assignments
1. Write a program to input a number. Pass it to a function and find
the reverse of the number. The function should return the reverse.
def reverse(num):
r=0
while num>0 :
d = num%10
r = r*10+d output
num = num//10 Enter an integer:25
return(r) Reversed number= 52
N= int(input("Enter an integer:"))
S=reverse(N)
print("Reversed number=",S)
Assignments
2. Write a program which calls a function that inputs 3 numbers and
find the average of the 3 numbers. The function should return the
result.
def average(a,b,c):
return((a+b+c)/3)
X= int(input("Enter an integer:"))
Y= int(input("Enter an integer:")) output
Z= int(input("Enter an integer:")) Enter an integer:10
A= average(X,Y,Z) Enter an integer:11
print("Average=",A) Enter an integer:12
Average= 11.0
Assignments
N= int(input("Enter an integer:"))
prime(N)
Assignments
def alternate(st):
print(st[::2])
output
Enter a string:welcome
wloe
Passing arguments
def Sum(a,b,c):
d=a+b+c OUTPUT
print(a,b,c,d) 12 34 23 69
def Sum(a,b,c=20):
def my_function(country = "Norway"): d=a+b+c
print("I am from " + country) print(d)
Sum(10,20,30)
my_function("India") Sum(10,40)
my_function() Sum(10) # type error, missing one
required positional argument
OUTPUT
OUTPUT 60
I am from India 70
I am from Norway
OUTPUT OUTPUT
60 Syntax error- Non default argument
80 follows default argument
70
Passing arguments
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it
reaches the function:
OUTPUT
apple
banana
cherry
Scope of a variable
Global Scope
A variable created in the main body of the Python code is a global
variable and belongs to the global scope.
Global variables are available from within any scope, global and
local.
• A name created declared in the top level segment(__main__) of a program is
said to have global scope and can be used in the entire program
• Variable defined outside all functions are global variables.
Global Keyword
If we want to use global variable inside the function, global keyword is used . to
modify a global variable inside a function. If you use the global keyword, the
variable belongs to the global scope. Once a variable is made global using
global keyword , it cannot be reverted.
def fun():
def fun(): global x
x+=25 # error,local var.x [Link] assignment x+=25
print("Inside function",x) print("Inside function",x)
x=300
x=300 print("before calling function",x)
print("before calling function",x) fun()
fun() print("After calling function",x)
print("After calling function",x)
OUTPUT
before calling function300
Inside the function 325
After calling function 325
Lifetime of a variable
In Python, the LEGB rule is used to decide the order in which the
variables are to be searched for scope resolution.
The scopes are listed below in terms of hierarchy (highest to
lowest/narrowest to broadest):
Always, a function will first look up for a variable name in its local
scope. Only if it does not find it there, the outer scopes are checked.
pi = 10
def inner():
pi = 30
print(pi)
Output:
inner() 30
Enclosed Scope :
For the enclosed scope, we need to define an outer() function enclosing the inner
function
pi = 10
def outer(): Output:
pi = 20 20
def inner():
print(pi)
inner()
outer()
For the print() function, inner() function
looks for a local variable pi which is not
found, it checks the enclosing scope
variable in the outer() function and pi is
selected from there.
Global Scopes :
# Global Scope
pi = 10 Output:
def outer(): 10
def inner():
print(pi)
inner()
outer()
Here call to outer() in turn calls inner() which looks for pi in local
first, then enclosing scope,then checks in global scope and
executes.
Built-in Scopes
WRITE
To summarise,
If a variable is not found in local scope, the higher scopes
WRITE
are looked up. If it is found in both enclosed and
global scopes. But as per the LEGB hierarchy, the
enclosed scope variable is considered even though we
have one defined in the global scope. If it is not there
in any of the scopes, then error is reported.
Mutable/immutable properties of
data objects with respect to function
WRITE Everything in Python is an object and every objects in Python can be
either mutable or immutable.
Since everything in Python is an Object, every variable holds an
object instance. When an object is initiated, it is assigned a unique object
id. Its type is defined at runtime and once set can never change,
however its state can be changed if it is mutable.
Means a mutable object can be changed after it is created, and
an immutable object can’t.
a+=b a+=b
b=*a # b*=a b*=a
print(a,b) print(a,b)
x,b=5 # indentation error, cannot unpack non iterable int object x,b=5,4
f1(x) # few parameters in function call f1(x,b)
OUTPUT:
9 36
Corrected code
define f2(x): def f2(x):
WRITE Global b global b
x+=b x+=b
b+=x+2
b+==x+2
print(x,y,b) print(x,b)
x,b=5,10
x,b=5,10 f2(b)
f2(b)
OUTPUT:
20 32
def f4(s):
for ch in s:
if ch in 'aeiou':
print('*',end='')
WRITE
elif ch in 'AEIOU':
print('#',end='')
elif [Link]():
print(s[0],end='')
else:
print(s[-1],end='')
f4('India')
print()
f4('Oman')
def f4(s):
for ch in s:
if ch in 'aeiou':
print('*',end='') #aa**
WRITE
elif ch in 'AEIOU':
#n*n
print('#',end='')
elif [Link]():
print(s[0],end='')
else:
print(s[-1],end='')
f4('India')
print()
f4('Oman')
Give output of the following program in Python
a=10
num=1 y=5
def myfunc(): def display(): def myfunc(a):
num=10 print("Hello") y=a
return num display() a=2
WRITE
print(num) print("bye!") print("y=",y,"a=",a)
print(myfunc()) print("a+y",a+y)
print(num) return a+y
print("y=",y,"a=",a)
print(myfunc(a))
print("y=",y,"a=",a)
def interest(prnc,time=2,rate=0.10):
return(prnc*rate*time)
WRITE
print(interest(6100,1))
print(interest(5000,3,0.12))
print(interest(time=4,prnc=5000))
print(interest(5000,rate=0.05,time=1))
Give output of the following program in Python
def interest(prnc,time=2,rate=0.10):
return(prnc*rate*time)
print(interest(6100,1))
print(interest(5000,3,0.12))
WRITE print(interest(time=4,prnc=5000))
print(interest(5000,rate=0.05,time=1))
610.0
1800.0
2000.0
250.0
Q1. Write a function max() to find the maximum of 3 integers. Accept the
integers from the user and pass it to the function max().The function max()
should return the maximum of the three. The result to be printed outside
the function.
WRITE Q2. Write a function sum() to find the sum of all numbers from a list.
Accept the list from the user and pass it to the function sum(). The result to
be printed from inside the function.
Q3. Write a function search() to search for a given number in a list. Accept
the list and the number to be searched within the function and display the
message “present in the list” or “not present in the list” from within the
function
Q6. Write a function even() to print all even numbers from a list. Accept the
list inside the function. The result to be printed from outside the function.
Q1. Write a function max() to find the maximum of 3 integers. Accept the
integers from the user and pass it to the function max().The function max()
should return the maximum of the three. The result to be printed outside
the function.
def max(x,y,z):
Output
WRITE if x > y and x > z :
return x Enter first integer :10
elif y > x and y > z : Enter second integer :30
return y Enter third integer :20
else: Maximum = 30
return z
Q2. Write a function sum() to find the sum of all numbers from a list.
Accept the list from the user and pass it to the function sum(). The result to
be printed from inside the function.
def sum(lst):
WRITE total = 0 Output
for x in lst :
total += x Enter the list elements:[2,3,4,5]
print("Sum=",total) Sum= 14
WRITE
Q3. Write a function search() to search for a given number in a list. Accept
the list and the number to be searched within the function and display the
message “present in the list” or “not present in the list” from within the
function
def search():
L= eval(input("Enter the list elements:"))
Output
num = int(input("Enter the number to be searched:"))
length =len(L) Enter the list elements:[2,3,4,5]
for i in range(0,length): Enter the number to be searched:3
if num == L[i]: 3 present in the list
print(num,"present in the list")
break Output
Enter the list elements:[2,3,4,5]
else :
Enter the number to be searched:6
print(num,"not present in the list")
6 not present in the list
search()
Q4. Write a function perfect() to check whether an integer is a perfect
number or not. Accept the number outside the function and pass it to the
function. Return the result to outside the function and display the result
form outside.
def perfect(x):
sum=0
WRITE
for i in range(1,x):
if x%i==0:
sum += i
if sum == x : Output
return 1
else: Enter the an integer:6
return 0 6 is a perfect number
num = int(input("Enter the an integer:"))
s = perfect(num)
if s== 1:
print(num, "is a perfect number")
else:
print(num,"is not a perfect number")
Q5. Write a function prime() to check whether an integer is a prime
number or not. Accept the number outside the function and pass it to the
function. display the result inside the function
def prime(x):
f=0
WRITE for i in range(1,x+1):
if x%i==0:
f += 1
if f == 2 : Output
print(x, "is a prime number")
else: Enter the an integer:5
5 is a prime number
print(x, "is not a prime number")
Output
num = int(input("Enter the an integer:")) Enter the an integer:6
prime(num) 6 is not a prime number
Q6. Write a function even() to print all even numbers from a list. Accept the
list inside the function . The result to be printed from outside the function.
def even():
WRITE
L= eval(input("Enter the list elements:")) Output
lst=[ ]
for x in L : Enter the list elements:[1,2,5,6]
if x%2==0: Even elements in the list are [2, 6]
[Link](x)
return lst
M=even()
print("Even elements in the list are ", M)
Q7. Write a program that receives two numbers in a function and returns
the results of all arithmetic operations on these numbers.
Q8. Write a program using functions to swap the values of two variables
through a function.
WRITE
Q9. Write a program using functions that takes a positive integer and
returns the one’s position digit of that integer.
Q10. Write a program using functions swap() that swaps the first and last
character of a string and display it.
Q7. Write a program that receives two numbers in a function and returns
the results of all arithmetic operations on these numbers.
def aritmetic():
n1= int(input("Enter the number:"))
n2= int(input("Enter the number:"))
lst=[]
add= n1+n2
WRITE [Link](add) Output
sub= n1-n2
[Link](sub) Enter the number:10
prod=n1 *n2 Enter the number:5
[Link](prod) Sum= 15
divide= n1/n2 Difference= 5
[Link](divide) Product= 50
return lst Division= 2.0
M=aritmetic()
print(“Sum=",M[0])
print(“Difference=",M[1])
print("Product=",M[2])
print("Division=",M[3])
Q8. Write a program using functions to swap the values of two variables
through a function.
def swap(n1,n2):
n1,n2 = n2,n1
print("Inside the function after swapping")
print("n1=",n1)
print("n2=",n2)
WRITE Output
a= int(input("Enter the number:"))
b= int(input("Enter the number:")) Enter the number:10
print("Before swapping:","a=",a,"b=",b) Enter the number:5
swap(a,b) Before swapping: a= 10 b= 5
Inside the function after swapping
n1= 5
n2= 10
Q9. Write a program using functions that takes a positive integer and
returns the one’s position digit of that integer.
def ones_position(n1):
return(n1%10)
WRITE Output
a= int(input("Enter the number:"))
x=ones_position(a) Enter the number:234
print("One’s Position digit is=", x) One’s Position digit is= 4
Q10. Write a program using function swap() that swaps the first and last
character of a string and display it.
WRITE
Q10. Write a program using functions swap() that swaps the first and last
character of a string and display it.
def swap(string):