Functions
Functions
CITY CAMPUS,
DALANWALA, DEHRADUN
Python language provide two important methods to import modules in a program which
1
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
are as follows:-
i. import statement- to import entire module
ii. from- to import all functions or selected ones
iii. import- to use modules in a program, we import them using the import statement
randint( )- This function generates the random integer values including two given numbers
(start and end values).
Syntax: randint(start, end)
It has two parameters. Both parameters must have integer values.
Example: import random n=random.randint(3,7)
It can generate number from 3 to 7 any one and will store in n.
Example2: What possible output(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the maximum values the
can be assigned to each of the variables FROM and TO. (CBSE Sample paper 2020)
import random
2
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
Ans. 2) 30#40#50
Maximum Value of FROM, TO is 3, 4
User Defined Functions: The functions those are defined by the user are called user
defined functions.
User defined functions:
The syntax to define a function is:
def function-name ( parameters) :
#statement(s)
Where:
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python. Parameters (arguments) through which we pass values to a
function. They are ptional.
A colon (:) to mark the end of function header.
One or more valid python statements that make up the function body. Statements must
have same indentation level. An optional return statement to return a value from the
function.
Example:
def display(name):
print("Hello " + name + " How are you?")
Function Parameters:
Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
Actual Parameter(Arguments): When a function is called, the values that are
passed in the call are called actual parameters. At the time of the call each actual
parameter is assigned to the corresponding formal parameter in the function
definition.
There are four different types of Actual Parameters(arguments) are available
in Python:
Default Parameters: Python allows function arguments to have default values.
If the function is called without the argument, the argument gets its default
value.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters z=x+y
3
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Positional Argumets:
Position-only arguments mean whenever we pass the arguments in the order we have
defined function parameters in which if you change the argument position then you
may get the unexpected output. We should use positional Arguments whenever we
know the order of argument to be passed.
Example:
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
nameAge(name="NS", age=75)
nameAge(age=14, name="Apoorva")
Keyword Arguments:
Keyword-only arguments mean whenever we pass the arguments(or value) by their
parameter names at the time of calling the function in Python in which if you
change the position of arguments then there will be no change in the output.
b.Function not returning any value : The function that performs some operations
but does not return any value, called void function.
def message():
print("Hello")
Here, we can see that the value of x is 20 initially. Even though the function
my_func()changed the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function)
from the one outside. Although they have same names, they are two different
variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a
global scope. We can read these values from inside the function but cannot change
(write) them. In order to modify the value of variables outside the function, they must
be declared as global variables using the keyword global.
MAIN( ) AS A FUNCTION: Including a main( ) function is not mandatory in Python. It
can structure our Python program in a logical way the puts the most important components of
the program into one function. It can also make our programs easier for non-python
programmers to read.
Example:- def DIS ( )
for i in range(1,11):
print(2 * i)
def main( ):
print(“Table of 2”)
DIS( )
In the above example, we have called the main( ) explicitly either from the shell or from the
script after giving the calling function for main( ) function in the end.
r=2
print( power(2,4))
Explanation:- In each call, the power function passes the actual parameters to the version
being called. The value of n is same for each power function call, but the value of s is
decremented by 1 for each call until s becomes 0. When s becomes 0, the function power( )
starts returning a value of n.
So answer will be 16
POINTS TO REMEMBER:
A module is separately saved unit whose functionality can be reused in any
other program.
A function is a named block of statements that can be invoked by its name.
Python can have three types of functions:-
1. Built in function
2. Function in Modules
3. User –Defined functions
A python module has the .py extension
There are two forms of importing Python module statements:
1. import <module names>
2. from <module> import <object>
Functions make program handling easier as only a small part of the program is
dealt with at a time, there by avoiding ambiguity.
Keyword arguments are the named arguments with assigned values being
passed in the function –call statement.
A function may or may not return a value.
A void function internally returns legal value None.
The program part(s) in which a particular piece of code or a data value(e.g.
variable) can be accessed is known as Variable Scope.
A local variable having the same name as that of a global variable hides the
global variables in its function.
A function is said to be recursive if it calls itself.
There are two cases in each recursive functions – the recursive case and base
case.
Short Answer Type Questions (1-Mark)
Q1. What is function?
Ans: A function in Python is a named block of statements within a program .That can be
invoked in any other part of the program.
7
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
Ans. An argument is data passed to a function through function call statement, for example
in the statement print (math.sqrt(64)) the integer 64 is an argument.
Q5. What is the difference between Local variable and Global Variable?
Ans. Local Variable:- It is a variable which is declared within a function or within a block. It is
accessible only within a function/block of a program
Global Variable: It is a variable which is declared outside all the function. It is accessible
throughout the program .
Q7. What are base case and recursive case? What is their role in recursive function?
Ans. In a recursive solution, the base cases are predetermined solutions for the simplest
version of the problem. If the given problem is a base case, no further computation is
necessary to get the result. The recursive case is the one that calls the function again with a
new set of values. The recursive step is a set of rules that eventually reduces all versions of
the problem to one of the base cases when applied repeatedly.
return(p*r*t)/100
Q11. Find and write the output of the following python code:
x=”abcdef”
i=”a”
while i in x:
print(i, end=” “)
Ans:- Answer is infinite time aaaaaaaaa…….
Q12. Find and write the output of the following python code:
a=10
def call( ):
global a
a=15
b=20
print(a)
call( )
Ans:- 15
Q13. Find and write the output of the following python code:
x=10
y=0
while x>y:
print(x,y)
x=x-1
y=y-1
Ans.: 10 0
9 1
8 2
7 3
6 4
Q1. Write a python program to sum the sequence given below. Take the input n from the
user.
Solution:
def fact(x):
j=1 , res=1
9
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
while j<=x:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
Q5. Find out option which is not possible from the following program:
import random
x=3
n=random.randint(0,x)
for i in range(n):
print(i, "#",i+1, end=" ")
i. 0 # 1 ii. 1 # 2 iii. 2 # 3 iv.3 # 4
Ans. Option iv. 3 # 4 is not possible.
Q6. Find and write the output of the following python code:
import random
Go = random.randint(0,3)
X= [100, 75, 10, 125]
for i in range( Go):
print(X[i], “$$”, end=” “)
i.100$$75$$10$$, ii.75$$10$$125$$, iii. 75$$10$$, iv.10$$125&&100
Q7. Find and write the output of the following python code:
def DISXII(s):
str2 = " "
for i in range (len(s)):
if s[i] not in "aeiouAEIOU":
str2=str2+s[i]
print(s)
print(str2)
P=20
Q=21
Q=func(P,Q)
print(P,Q)
P=func(Q)
print(P,Q)
Q=Func(P)
print(P,Q)
Ans:- 20 20
14 20
14 14
Q9. Find and write the output of the following python code:
def Check(N1=1, N2=2):
N1=n1 + n2
N2= N2+1
print(N1, N2)
Check( )
Check(2, 1)
Check(3)
Ans. 33
32
53
Q10. Find and write the output of the following python code:
def Exec(B, C=100):
Temp = B + C
B= B + Temp
If c = = 100:
print(Temp, B, C)
M= 90
N= 10
Exec(M)
print(M, N)
Exec(M,N)
print(M, N)
Q11. Find and write the output of the following python code:
12
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
def DIS( ):
R= 1
Num= 65
while R < = 5:
J= 1
while J<=R:
print(chr(num), end=” “)
J=J+1
Num= Num + 1
print( )
R = R+1
DIS( )
Ans: A
BC
DEF
GHIJ
KLMNO
Q12. Write a program to enter a number and using function print its factorial.
def Factorial(x):
F=1
while x > 0:
F=F*x
x=x–1
print(“factorial of entered number=”, F)
Q13. Write a function which will accept a string as argument and find out it is Palindrome or
not.
St =input(“Enter String”)
Palindrome(St)
13
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
Q14. Write a function which will accept a List and reverse the List without using reverse.
Ans: def Rev(Lst):
F=0
R=len(Lst)-1
while F < R:
Temp = Lst[F]
Lst[F] = Lst[R]
Lst[R] = Temp
F=F+1
R=R–1
print(Lst)
Q16. Write a function in Python Reverse(X), which will print all elements of list X in reverse
order after multiplying by 4 .
Example:- 2 5 12 4 8 10
Then output will be like: 40 32 16 48 20 8
Ans:- def Reverse( X):
for K in range(len(X)-1,-1,-1):
print(X[i] *4,end = “ “)
Q17. Write a user defined function which will accept an integer list and its length and an
element as parameter and print “Found” with its location if element is available
otherwise print “Not Found”.
Ans:- def DIS( List, R,ele):
C= -1
for I in range (0, R):
if List[I]==ele:
C=I
if C== -1 :
print(Not Found”)
else:
print(“Found at = “,C)
Q18. Write a user defined function which will accept an integer list and its length as
parameter and delete each negative numbers from the list.
Ans:- def DELNEGATIVE(X, R):
K=0
while K <R:
14
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
if X[K]<0:
del X[K]
R=R-1
print(“List after deletion=”,X)
UNSOLVED QUESTIONS:
C. SHORT ANSWERS:
i. A program having multiple functions is considered better designed than a program
without any function. Why?
ii. Describe the different types of functions in Python using appropriate examples.
iii. What is the difference between local and global variables?
iv. Differentiate between random.random( ) function and random.randint() function.
v. What do you mean by Lifetime of a variable?
vi. When function returns None in Python program?
vii. Write a Python function that takes a number as a parameter and checks whether
number is prime or not.
viii. Write a function that takes a List as a parameter and return greatest number.
CBSE BOARD 2013
ix. Write a function that takes a String as a parameter and print at first vowels then
print all consonants.
x. Write a function that takes a List as a parameter and Write a user-defined function
NoTwoThree(LIST,N) where N is length of list ,which should display the value of
all such elements and Their corresponding locations in the List (i.e the List index),
15
DOON INTERNATIONAL SCHOOL
CITY CAMPUS,
DALANWALA, DEHRADUN
which Are not multiples of 2 or 3. N represents the total number of elements in the
List, to be checked. Example: if the List contains 1 2 3 4 25 8 12 49 9
Then the function should display the output as:
25 at location 0
49 at location 3 CBSE BOARD 2019
xii. Write a function which will accept an integer list and its size as parameter and
exchange first half elements of list with second half elements assuming list is
having even number of elements.
xiii. Write a function which will accept an integer list and its size as parameter and
shift the negative numbers to right and the positive numbers to left so that the
resultant list looks like:
Original List : [ -12, 11, -13, -5, 6, -7, 5, -3, -6]
Output List :[11, 6, 5, -12, -13, -7, -3, -6]
xv. Write a function which will accept a list and its size as parameter and print sum of
all numbers which are ending with 3. Ensure that the function is able to handle
various situations viz. , list containing numbers and strings.
e.g. List[ 33, 13, “RAM”, “AYUSH”, 92, 3, “RASHMI”, 12]
16