0% found this document useful (0 votes)
12 views30 pages

Understanding Functions in Python

The document provides a comprehensive overview of functions in programming, particularly in Python. It covers the definition, advantages, types, creation, and execution flow of functions, along with examples of user-defined, void, and non-void functions. Additionally, it discusses parameters, return values, and includes quizzes and assignments for practical understanding.
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)
12 views30 pages

Understanding Functions in Python

The document provides a comprehensive overview of functions in programming, particularly in Python. It covers the definition, advantages, types, creation, and execution flow of functions, along with examples of user-defined, void, and non-void functions. Additionally, it discusses parameters, return values, and includes quizzes and assignments for practical understanding.
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

Chapter : Functions

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 ?

A function is a named unit of a program


(subprogram) which can execute a
group of statements to perform a
specific task.

Why do we need functions ?


L. arge programsbecome easy to handle when
broken down in smaller units.
Function Introduction
To understand functions, let us take real world scenario:
In mathematics we define functions in polynomials:
Eg f(X) = 2X3+3X
when X =1, f(1)=2x13+3x1=5
when X =2, f(2)=2x23+3x2=22
when X =7, f(7)=2x73+3x7=364
And so on.
In the same manner, in Python programs, functions are
written to execute same set of statements for different
values.

Advantages of functions

 Program development made easy and fast : Large programs


when divided into modules, development becomes easy as only
a small amount of code is handled in each module.
 Program testing becomes easy : Easy to locate and debug
the errors.
 Code sharing : Same function can be made available to other
programs.
 Code re-usability : when function is called more than once in
the same program with different values, same function code can
be reused.
 Increases program readability : Main program size gets
reduced.

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

Defining a user defined function

 Every function should start with keyword def.


 Every function should have a name(identifier).
 Functions may have parameters or arguments (optional).
 Function header containing def keyword should end with :
 Function may or may not return value

Syntax:
def functioname(argument/parameter list): #
statements in the function

Creating & calling a Function(user defined)

def my_own_function(): #Function block/


definition/creation
print("Hello from a function")
#program starts here. program code
print("hello before calling a function")
my_own_function() #function call. now function codes will be executed
print("hello after calling a 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.

Functions – properties of function

 A function gets executed only when it is called


(function call).
 We can pass data, known as parameters, into a
function.
 A function can return data as a result.
.

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…

def printWeather(): # line 1


print("It is sunny!") #line 2
A. the function call
B. the function body
C. the function definition
D. the function header
E. the function declaration

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.

Arguments that are received in the function(function header) are


called formal arguments Or formal parameters. They can be
variables only.

Program to print power of a number using


function
def power(a): # a is formal parameter
print(a**2)

X=10 # X, 3, X+2 are actual parameters


power(X) # function is called thrice (code
power(3) reusability feature)
power(X+2)
Output
100
9
144

Void and non void functions

Void functions are functions which do not return a


value. These functions will not have return
statement.

Non Void functions are functions which return


value(s). These functions will have return
statement.
Void and non Void functions
Void function Non Void function
def sum(a,b): def sum(a,b):
c=a+b c=a+b
print ("Sum is ",c) return(c) #return statement

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

Note: In this case function call can be given


as print(sum(X,Y)) instead of using extra
variable P. [Replace last two statements]

Non Void functions


In this case function call can be given as
Non Void function argument to print () function [Replace last two
statements]

def sum(a,b): def sum(a,b):


c= a+b c=a+b
return(c) #return statement return(c)#return statement

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

Void and non void functions

Functions can be defined in 4 different ways :

Void functions without parameters(No formal parameters, no return value)


Void functions with parameters (with formal parameters, no return value)

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

def sum(): def sum(a,b):


a=10 c = a+b
b=30 print(" SUM IS",c)
c=a+b
print(" SUM IS",c) X=10
sum() Y=30
sum(X,Y)

OUTPUT
OUTPUT
SUM IS 40
SUM IS 40

Non Void functions

# case 3: Non Void functions without arguments # case 4: Non Void functions with arguments

def sum(): def sum(a,b):


a=10 c=a+b
b=30 return (c )
c= a+b
return c X=10
P=sum() Y=30
print("SUM IS ",P) Z=sum(X,Y)
print(" SUM IS ",Z)
OUTPUT
SUM IS 40 OUTPUT
SUM IS 40

Write a program to input a number. Pass


this to a function factorial() which finds
factorial of the number.
def factorial(n): OUTPUT
if n<0: Enter a number 5
print("Error") Factorial is 120

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.

def Simple_interest(a,b,c): def Simple_interest(a,b,c):


si=a*b*c/100 si=a*b*c/100
print ("Simple interest=", si) return(si)

p=int(input("Enter Principal amount")) p=int(input("Enter Principal amount"))


r=int(input("Enter Rate"))
r=int(input("Enter Rate"))
t=int(input("Enter time in years"))
t=int(input("Enter time in years")) S=Simple_interest(p,r,t)
Simple_interest(p,r,t) print("Simple interest=",S)

Enter Principal amount 1000 Enter Principal amount 1000


Enter Rate 3 Enter Rate 3
Enter time in years 2 Enter time in years 2
Simple interest = 60.0 Simple interest = 60.0

Functions Part- 2

Returning values from functions


Multiple functions in a program
Calling function inside another function
Defining function inside another function
Passing arguments – Positional, Keyword, Default arguments

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

A return statement ends the function


def sum(a,b)
c=a+b
return (c)
print(c) # unreachable code, never executed OUTPUT
40
X=10
Y=30
Z=sum(X,Y):
print(Z)

Non Void functions – Returning more than one


value

def power(a):
return a**2,a**3

X=10 OUTPUT
100 1000
Y,Z=power(X)
print(Y,Z)

If a non void function


returns more than one
value, same number of
variables should be
assigned while calling
the function
Non Void functions – Returning more than one
value

def power(a): If a non void function


return a**2,a**3 returns more than one
X=10 OUTPUT value, if only one variable
(100,1000) is receiving the function
Y=power(X)
print(Y) call value, then it returns
a tuple.

Multiple functions in a program def sum(a,b):


c= a+b
print("Sum is ",c)
We can have def difference(a,b):
any number c=a-b
of functions in print("Difference is ",c)
a single def product(a,b):
program c=a*b
print("Product is ",c)
def divide(a,b):
c=a/b
print("Division result ",c)
X=10
Output Y=30
Sum is 40 sum(X,Y) #function call
Difference is -20 difference(X,Y) #function call
Product is 300 product(X,Y) #function call
Division result 0.3333333333333333
divide (X,Y) #function call
Multiple functions in a program
Menu driven program to simulate a calculator using
functions based on a choice.

def sum(a,b): X=10


c=a+b Y=30
print("MENU\[Link]\[Link]\[Link]\n4.
print("Sum is ",c) DIVIDE ")
def difference(a,b): op=int(input("Enter a choice(1-4)"))
c=a-b if op==1:
print("Differnce is ",c) sum(X,Y) #functioncall
def product(a,b): elif op==2:
difference(X,Y) #function call
c=a*b elif op==3:
print("Product is ",c) product(X,Y) #function call
def divide(a,b): elif op==4:
c=a/b divide(X,Y) #function call
print(“Division result is ",c) else:
print("Wrong choice ")
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.
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.
3. Write a function which checks whether the number passed to it is
prime or not.
4. Write a program to input a string. Pass it to a function and function
should print every alternate character of the string.

Calling a function inside another function We can call a function inside


another function in a program

Write a program which inputs 3 numbers ,passes them to a function sum_of_squares()


which finds sum of squares of these numbers using another function Square() which
returns square of the argument.
def Square(x):
return x*x

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)

Function defined inside another function

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

3. Write a function which checks whether the number passed to it


is prime or not.
def prime(num):
f=0
for i in range(1,num+1):
if(num%i == 0):
f+=1
if(f==2): output
print(num,"is a Prime Number") Enter an integer:5
else: 5 is a Prime Number
print(num,"not a Prime Number")

N= int(input("Enter an integer:"))
prime(N)
Assignments

4. Write a program to input a string. Pass it to a function and


function should print every alternate character of the string.

def alternate(st):
print(st[::2])

Str= input("Enter a string:")


alternate(Str)

output
Enter a string:welcome
wloe

Passing arguments

There are 3 types of arguments

Positional arguments (Required arguments)


Keyword arguments
Default arguments

Passing arguments - positional arguments (Required


arguments)
Arguments must be provided for all
parameters
def my_function(fname,lname): #2 formal parameters
print(fname + " " + lname)
OUTPUT
Computer text
my_function("Computer","text“) # 2 actual parameter

def my_function(fname, lname): # 2 formal parameters


print(fname + " " + lname)
OUTPUT
type error:
my_function("Computer") # 1 actual parameter
my_function() missing
one required positional
argument: ʹlname
Passing arguments-keyword arguments
• Keyword arguments - the caller identifies the actual
arguments by the formal parameter name. Arguments can
be written in any order providing their name during function
call

def Sum(a,b,c):
d=a+b+c OUTPUT
print(a,b,c,d) 12 34 23 69

Sum(b=34,c=23,a=12) # function call identifies variables by name

Passing arguments-default arguments

Parameters can be given default values. If corresponding


argument is missing, function will take default value.

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

Passing arguments-default arguments


More than one parameter can be given default values, but all default values
should be provided to the right. If corresponding argument is missing, function
will take default value.

def Sum(a,b=40,c=20): def Sum(a=30,b,c=20): #Syntax error


d=a+b+c
d=a+b+c
print(d) print(d)
Sum(10,20,30) Sum(10,20,30)
Sum(10,50) Sum(10,50)
Sum(10) Sum(10)

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:

def my_function(food): #parameter food is treated as list


for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)

OUTPUT
apple
banana
cherry

Scope of a variable

A variable is only available from inside the region it is


created. This is called scope.
Local Scope
•A variable created inside a function belongs to the local
scope of that function, and can only be used inside that
function.
def myfunc(): #the variable x is not available outside the
x = 300 function, but it is available for any function
def myinnerfunc(): inside the function.
print(x) x can be accessed by myfunc() and
myinnerfunc() myinnerfunc()
myfunc()

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.

x=300 # Global variable A variable created outside of a


function is global and can be used
def change(): by any function inside the program
y=x+20
print("Inside the function",x) OUTPUT
Before calling the function300
print("y=",y)
Inside the function300
print("Before calling the function",x) y=320
change() After calling the function300
print("After calling the function",x)
Naming Variables (Global and local variables having same name)
When a global variable and a local variable are having same name, Python will
treat them as two separate variables, one available in the global scope (outside
the function) and one available in the local scope (inside the function) . In other
words, in such a situation local variable hides the global variable inside the
function.
x = 300
The function will print the local x
def myfunc(): and then the code will print the
x = 200 global x
print("Inside the function",x)
x=x+20
print(x) OUTPUT
print("Inside the main",x) Inside the main 300
myfunc() Inside the function 200
print(“After calling function",x) 220
After calling function 300

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

Lifetime of a variable is the time for which a variable or


name remains in memory is called lifetime of variable

For global variables, lifetime is entire program run.

For local variable, life time is their functions run(as long


as function is being executed)
Lifetime of a variable
x is a global variable . Its lifetime is in the entire program. The value of x can be
changed by the function.
y is a local variable of function change(). Its lifetime is within the function
change().
a is a local variable of main function part. Its lifetime is within main function part.
x=300
def change():
y=x+20 OUTPUT
print("Inside the function",x) Before calling the function 300
print("y=",y) Inside the function 300
print("Before calling the function",x) y=320
a=40 After calling the function 300 310
a=x+10
change()
print("After calling the function",x,a)

Name resolution rule (LEGB)

For every name reference ,when you access a variable within a


program, Python follows name resolution rule (LEGB)

LEGB - LOCAL, ENCLOSED,GLOBAL,BUILT-IN

SCOPE RESOLUTION USING LEGB RULE

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):

•Local(L): Defined inside function/class


•Enclosed(E): Defined inside enclosing functions(Nested
function concept)
•Global(G): Defined at the uppermost level
•Built-in(B): Reserved names in Python built-in moduleS
Local scope

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

On running the above program, the execution of the inner function


prints the value of its local(highest priority in LEGB rule)
variable pi because it is defined and available in the local scope.

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 :

If a variable is not defined in local scope, or enclosed scope then, it is checked


for in the higher scope, the global scope.

# 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

The final check can be done by importing pi from math module


Output:
3.141592653589793
# Built-in Scope from math
from math import *
Here , pi is not defined in either local,
def outer():
enclosed or global scope, the built-in
def inner(): scope is looked up i.e the pi value
print(pi) imported from math module. Since
the program is able to find the value
inner() of pi in the outermost scope, the
outer() output is obtained

SCOPE RESOLUTION USING LEGB RULE

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.

Mutable objects: list, dict, set


Immutable objects: int, float, complex, string, tuple.
Passing a mutable type to a function
passing a dictionary to function
passing a list to function
WRITE
def change(p):
def updateList(list1): p[2]="TOYOTA"
print(p)
list1 +=[10] D={1:"FORD",2:"FERRARI",3:"BENZ"}
[Link](100) change(D)
print(D)
Output
{1:"FORD",2:"TOYOTA",3:"BENZ"}
n = [50, 60] Outpu t {1:"FORD",2:"TOYOTA",3:"BENZ"}
[50 6 0 10 100]
updateList(n)
print(n) When Mutable objects are passed,
changes in function is reflected in
actual parameters after the function.

Passing a immutable type to a function


passing integer to function
WRITE
passing a string to function def fun1(x,y):
def change(p): x,y=x-20,y+10
p="Good morning" print("Inside function",x,y) Inside function 80 210
print(p) Output After call 100 200
s="I LOVE INDIA" Good morning
change(s) I LOVE INDIA
print(s) x,y=100,200
fun1(x,y)
print("After call",x,y)

Immutable objects (actual parameters) remain


unchanged after function call

Writing function inside _main_


print("main program")
a=10
WRITE
def fun(): #local function
global a main program
10
print ("my function") my function
20
a=a+10
print(a)
print(a)
fun()
Find error(s), if any, in each of the following code snippets in Python:

WRITE Corrected code

def f1[a,b] # syntax error . It should be def f1(a,b): def f1(a,b):

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

Find error(s), if any, in each of the following code snippets in Python:

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

GIVE OUTPUT of the following python programs

def f1(a,b): def f2(x,y):


def f1(a,b):
global x global b
a+=b
a+=b x+=b
b*=a
WRITE b*=a b*=y
print(a,b)
x=x+100 y+=x+y
x,b=5,10 print(x,y,b)
print(a,b)
f1(x,b) x,b=5,10
x,b=5,10
print(x,b) f2(x,b)
f1(x,b)
print(x,b) print(x,b)
GIVE OUTPUT of the following python programs

def f1(a,b): def f2(x,y):


def f1(a,b):
global x global b
a+=b
a+=b x+=b
b*=a
WRITE b*=a b*=y
print(a,b)
x=x+100 y+=x+y
x,b=5,10 print(x,y,b)
print(a,b)
f1(x,b) x,b=5,10
x,b=5,10
print(x,b) f2(x,b)
f1(x,b)
print(x,b) print(x,b)
15 150
15 35 100
5 10 15 150
5 100
105 10

Give output of the following program in Python

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')

Give output of the following program in Python

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)

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)
1 Hello
10 bye! y= 5 a= 10
1 y= 10 a= 2
a+y 12
12
y= 5 a= 10

Give output of the following program in Python

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

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
from outside.
Q5. Write a function prime() to check whether an integer is a prime
WRITE
number or not. Accept the number outside the function and pass it to the
function, display the result inside 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

n1 = int(input("Enter first integer :"))


n2 = int(input("Enter second integer :"))
n3 = int(input("Enter third integer :"))
print("Maximum =",max(n1,n2,n3))

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

L= eval(input("Enter the list elements:"))


sum(L)

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.

Python string is immutable which means we cannot modify it directly. But


Python has string slicing which makes it very easier to perform string
WRITE
operations and make modifications. Follow the below steps to swap
characters –
• We initialize a variable start, which stores the first character of the string
(string[0])
• We initialize another variable end that stores the last character (string[-1])
• Then we will use string slicing, string[1:-1], this will access all the
characters from the 2nd position excluding the last character.
• Then we add these three as required forming a new string that has the first
and last characters of the original string swapped. And then we will print 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):

# storing the first character Output


start = string[0]
Enter the string:Welcome
# storing the last character eelcomW
end = string[-1]

swapped_string = end + string[1:-1] + start


print(swapped_string)

str=input(“Enter the string:”)


swap(str)
RECAP - FUNCTIONS
Functions – types, syntax Flow of execution in function
Arguments- positional,keyword,default Void ,non void
functions
Returning values from functions Scope of variable ,
global local scopes
Lifetime of a variable,Lifetime of global, local variables
LEGB rule in name resolving
global keyword
Mutable and immutable object passing
Give the output , Find error type questions

You might also like