0% found this document useful (0 votes)
3 views

Python Function Material

The document provides an overview of Python functions, explaining their definition, usage, and types. It covers topics such as function parameters, arguments, indentation, and the return statement, along with examples for clarity. Additionally, it discusses built-in and user-defined functions, as well as different types of function arguments.

Uploaded by

ckamali5311
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)
3 views

Python Function Material

The document provides an overview of Python functions, explaining their definition, usage, and types. It covers topics such as function parameters, arguments, indentation, and the return statement, along with examples for clarity. Additionally, it discusses built-in and user-defined functions, as well as different types of function arguments.

Uploaded by

ckamali5311
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/ 23

2 Python Functions

1. What is a function in python?


Ans. A function is a block of organised, reusable code that is used to perform a single, related action. Functions provide
better modularity for your application and a high degree of code reusing.
Python gives many built-in functions like print(), etc. but you can also create your own functions. These functions
are called user-defined functions.
You can pass data, known as parameters, into a function.
A function can return data as a result.
2. What is the role of indentation in python function.
Ans. Indentation (Space) in Python Functions
Python functions don’t have any explicit begin or end like curly braces to indicate the start and stop for the
function, they have to rely on this indentation. It is also necessary that while declaring indentation, you have to
maintain the same indent for the rest of your code.
3. How to define user define function?
Ans. Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters
inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function or
docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
“function_docstring”
function_suite
return [expression]
4. How to call a function in python ? Explain with an example.
Ans. Calling a Function: To call a function, use the function name followed by parenthesis.
Example:
def fun():
print(“Hello”)
fun() # function calling
output
Hello
Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 43
5. Give the output
def prn():
print(“****”)
print(“hello”)
prn()
print(“hi”)
prn()
print(“bye”)
prn()
Ans. hello
****
hi
****
bye
****
6. What is Parameter in python function?
Ans. Information can be passed to functions as parameter. Parameters are specified after the function name, inside the
parentheses. You can add as many parameters as you want, just separate them with a comma.
7. What is the difference between parameter and argument?
Ans. Parameters are temporary variable names within functions.
The argument can be thought of as the value that is assigned to that temporary variable.
For instance, lets consider the following simple function to calculate sum of two numbers.
def sum(a,b):
return a+b
sum(10,20)
a,b here are the parameter for the function ‘sum’.
Arguments are used in procedure calls, i.e. the values passed to the function at run-time.10,20 are the arguments
for the function sum
8. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example for each. [SP 21]
Ans. The list of identifiers used in a function call is called actual parameter(s) whereas the list of parameters used in
the function definition is called formal parameter(s).
Actual parameter may be value/variable or expression.Formal parameter is an identifier.
Example:
def area(side): # line 1
return side*side;
print(area(5)) # line 2
In line 1, side is the formal parameter and in line 2, while invoking area() function, the value 5 is the actual
parameter.
A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a
function call.
9. What are the different types of Functions in python?
Ans. There are two basic types of functions: built-in functions and user defined functions.
(i) The built-in functions are part of the Python language; for instance dir() , len() , or abs() .
(ii) The user defined functions are functions created with the def keyword.

44 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
10. Explain the types of function arguments in python
Ans. Function Arguments: You can call a function by using the following types of formal arguments:
• Required arguments • Keyword arguments
• Default arguments • Variable number of arguments
• Arguments are passed as a dictionary.
(i) Required arguments: Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with the function definition.
def show(x,y):
print(“Name is “,x)
print(“Age is “,y)
show(“Raj”,18)
Output:
Name is Raj
Age is 18
(ii) Keyword arguments: Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to
place argument out of order because the Python interpreter is able to use the keywords provided to match
the values with parameters.
def show(x,y):
print(“Name is “,x)
print(“Age is “,y)
show(y=18,x=”Raj”)
OUTPUT
Name is Raj
Age is 18
(iii) Default arguments: A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on default arguments.
def sum(a,b=10):
print(‘sum is’,a+b)
sum(15,25)
sum(15)
OUTPUT
sum is 40
sum is 25
The rule for placing the default arguments in the argument list : Once default value is used for an
argument in function definition, all subsequent arguments to it must have default value. It can also be stated
as default arguments are assigned from right to left.
(iv) Variable Number of Arguments: In cases where you don’t know the exact number of arguments that you
want to pass to a function, you can use the following syntax with *args:
The variable stored in *args are represented in the form of tuple.
def change(*a):
for i in a:
print(i)
print(a)

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 45
change(10,5)
change(15,20,25)
OUTPUT
10
5
(10, 5)
15
20
25
(15, 20, 25)
(v) Arguments are passed as a dictionary (**kwargs): Kwargs allow you to pass keyword arguments to a
function. They are used when you are not sure of the number of keyword arguments that will be passed in
the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double
asterisk notation ( ** ).
In the function, we use the double asterisk ** before the parameter name to denote this type of argument.
The arguments are passed as a dictionary and these arguments make a dictionary inside function with name
same as the parameter excluding double asterisk **
Example:
def fun(**data):
print(“\nData type of argument:”,type(data))
print(data)
for key, value in data.items():
print(key,value)
fun(Name=”Aman”,Age=18,Marks=56)

output
Data type of argument: <class ‘dict’>
{‘Name’: ‘Aman’, ‘Age’: 18, ‘Marks’: 56}
Name Aman
Age 18
Marks 5
11. How does a function return Value?
Ans. If you want to continue to work with the result of your function and try out some operations on it, you will need
to use the return statement to actually return a value.
Example:

def square(x):
return x * x
a=5
print(square(3))
print(square(a))
OUTPUT
9
25
46 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
12. Can a function return multiple values? Explain with an example.
Ans. Yes, the return values should be a comma-separated list of values and Python then constructs a tuple and returns
this to the caller,
Example:
def change(a,b,c,d):
m=max(a,b,c,d)
n=min(a,b,c,d)
s=a+b+c+d
return n,m,s
g,h,i=change(2,5,7,20)
print (g,h,i)
OUTPUT
2 20 34
or
def change(a,b,c,d):
m=max(a,b,c,d)
n=min(a,b,c,d)
s=a+b+c+d
t=(n,m,s)
return t
t1=change(2,5,7,20)
print (t1)
g,h,i=t1
print(g,h,i)
OUTPUT
(2, 20, 34)
2 20 34
13. Explain docstrings in python functions?
Ans. Another essential aspect of writing functions in Python: docstrings. Docstrings describe what your function does,
such as the computations it performs or its return values. These descriptions serve as documentation for your
function so that anyone who reads your function’s docstring understands what your function does, without having
to trace through all the code in the function definition.
Function docstrings are placed in the immediate line after the function header and are placed in between triple
quotation marks.
def change(x):
‘’’check call by value’’’
x=[7]
print(x)
print(change.__doc__)
a=[5,2,3,1]
change(a)
print(a)
OUTPUT
check call by value
[7]
[5, 2, 3, 1]

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 47
Output: Functions
14. Give the output 16. Give the output
(i) print(“hi”) def sum(a,b):
def abc(): print(“sum is “,a+b)
print(“hello”) x=5
print(“bye”)
y=10
abc()
sum(x,y)
(ii) def abc():
print(“hello”) sum(20,40)
print(“hi”) Ans. Output
print(“bye”) sum is 15
abc() sum is 60
(iii) print(“hi”)
17. Give the output of the following program
print(“bye”)
def check(a):
def abc():
print(“hello”) for i in range(len(a)):
abc() a[i]=a[i]+5
Ans. OUTPUT return a
(i), (ii), (iii) b=[1,2,3,4]
hi c=check(b)
bye print(c)
hello Ans. OUTPUT
15. Give the output 2 [SP 16] [6, 7, 8, 9]
def cal():
i = 9 18. Give the output
while i> 1: def sum(*a):
if i%2==0: s=0
x = i%2 for i in a:
i = i-1 s=s+i
else: print(s)
i = i-2 sum(2,3)
x = i sum(2,6,3)
print (x**2)
sum(1,2,3,4)
cal()
Ans. OUTPUT
Ans. 49
5
25
9 11
1 10

Output: Default Parameter


19. Give the output abc(a)
def abc(x,y=60): abc(b)
print(x+y) Ans. output
a=20 50
b=30 80
abc(a,b) 90

48 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
20. Give the output 23. Find and write the output of the following Python
def abc(a=2,b=4):
code : 3 [comptt 19]
def Alter(P=15,Q=10):
return a+b
P=P*Q
x=10
Q=P/Q
y=20
print (P,”#”,Q)
x=abc(x,y)
return Q
print(x,y)
A=100
y=abc(x)
B=200
print(x,y)
A=Alter(A,B)
x=abc(y)
print (A,”$”,B)
print(x,y)
B=Alter(B)
Ans. output
print (A,”$”,B)
30 20
A=Alter(A)
30 34
print (A,”$”,B)
38 34
21. Give the output Ans. 20000 # 100.0
def abc(x,y=60):
100.0 $ 200
2000 # 200.0
return x+y
100.0 $ 200.0
a=20
1000.0 # 100.0
b=30
100.0 $ 200.0
a=abc(a,b)
24. Find and write the output of the following python
print(a,b)
program code:
b=abc(a) def Revert(Num,Last=2):
print(a,b) if Last%2==0:
a=abc(b) Last=Last+1
print(a,b) else:
Ans. OUTPUT Last=Last-1
50 30 for C in range(1,Last+1):
50 110 Num+=C
170 110 print(Num)
A,B=20,4
22. Give the output
Revert(A,B)
def abc(x=50,y=60):
B=B-1
return x+y
Revert(B)
a=20
Ans. 35
b=30 9
b=abc(a,b)
25. Find and write the output of the following python
print(a,b) code: 3[2019]
a=abc(b,a) def Convert(X=45,Y=30):
print(a,b) X=X+Y
a=abc(a,b) Y=X-Y
print(a,b) print (X,”&”,Y)
Ans. output return X
20 50 A=250
70 50 B=150
120 50 A=Convert(A,B)

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 49
print (A,”&”,B) 28. Find and write the output of the following python
B=Convert(B) code: [2] [comptt 2020]
print (A,”&”,B) def Call(P=40,Q=20):
A=Convert(A) P=P+Q
print (A,”&”,B)
Q=P-Q
Ans. 400 & 250
print(P,’@’,Q)
400 & 150
180 & 150 return P
400 & 180 R=200
430 & 400 S=100
430 & 180 R=Call(R,S)
26. Find and write the output of the following python print (R,’@’,S)
code: 3[2019] S=Call(S)
def Changer(P,Q=10):
print(R,’@’,S)
P=P/Q
Q=P%Q
Ans. 300 @ 200
print (P,”#”,Q) 300 @ 100
return P 120 @ 100
A=200 300 @ 120
B=20
29. Find and write the output of the following python
A=Changer(A,B)
code: [3][comptt 2020]
print (A,”$”,B)
def Assign(P=30,Q=40):
B=Changer(B)
P=P+Q
print (A,”$”,B)
A=Changer(A) Q=P-Q
print (A,”$”,B) print (P, ‘@’,Q)
Ans. 10.0 # 10.0 return P
10.0 $ 20 A=100
2.0 # 2.0 B=150
10.0 $ 2.0
A=Assign(A,B)
1.0 # 1.0
print (A, ‘@,B)
1.0 $ 2.0
B=Assign(B)
27. Find and write the output of the following python
code: 3[SP 2020] print (A,’@’,B)
def Change(P ,Q=30): Ans. 250 @ 100
P=P+Q 250 @ 150
Q=P-Q 190 @ 150
print( P,”#”,Q)
250 @ 190
return (P)
R=150 30. Give the output
S=100 def calc(u):
R=Change(R,S) if u%2==0:
print(R,”#”,S) return u+10;
S=Change(S) else:
Ans. 250 # 150 return u+2;
250 # 100
def pattern(M,B=2):
130 # 100
50 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
for CNT in range(0,B): return M*3
print(calc(CNT),M,end=””); else:
print() return M+10;
pattern(“*”) def Output(B=2):
pattern(“#”,4) for T in range (0,B):
pattern(“@”,3) print(Execute(T),”*”,end=””)
Ans. OUTPUT print()
10 *3 *
Output(4)
10 #3 #12 #5 # Output()
10 @3 @12 @ Output(3)
31. Give the output Ans. 0 *11 *12 *9 *
def Execute(M): 0 *11 *
if M%3= =0: 0 *11 *12 *

OUTPUT : Random
32. What’s the difference between randrange and randint?
Ans. Difference between.
randint randrange
randint(x,y) will return a value >= x and <= y. It will generate randrange(x,y) will return a value >=x and < y. The randrange(start,
a random number from the inclusive range. stop, step) doesn’t include the stop number while generating random
integer, i.e., it is exclusive.
This function takes two parameters. Both are mandatory. The This function takes three parameters(start,stop,step). Out of three
randint (start, stop) includes both start and stop numbers while parameters, two parameters are optional. i.e., start and step are the
generating random integer. optional parameters. The default value of start is 0, if not specified.
The default value of the step is 1, if not specified.
For example, random.randint(0, 100) will return any random random.randrange(0, 100) will return any random number between
number between 0 to 100 (both inclusive). 0 to 99. such as 0, 1, 2, …99. It will never select 100.

33. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable NUMBER. 2 [D 15]
import random
STRING=”CBSEONLINE”
NUMBER=random.randint(0,3)
N=9
while STRING[N]!=”L”:
print (STRING[N] +STRING[NUMBER] + “#”,end=””)
NUMBER=NUMBER+1
N=N-1
(i) ES#NE#IO# (ii) LE#NO#ON# (iii) NS#IE#LO# (iv) EC#NB#IS#
Ans. (i) ES#NE#IO# (iv) EC#NB#IS#
Minimum value of NUMBER = 0
Maximum value of NUMBER = 3
34. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable COUNT. 2 [OD 15]
import random
TEXT=”CBSEONLINE”

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 51
COUNT=random.randint(0,3)
C=9
while TEXT[C]!=’L’:
print (TEXT[C] + TEXT[COUNT] + ‘*’,end=””)
COUNT=COUNT+1
C=C-1
(i) EC*NB*IS* (ii) NS*IE*LO* (iii) ES*NE*IO* (iv) LE*NO*ON*
Ans. (i) EC*NB*IS* (iii) ES*NE*IO*
Minimum COUNT = 0
Maximum COUNT = 3
35. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable ROUND. 2 [comptt 17]
import random
PLAY=[40,50,10,20]
ROUND=random.randint(2,3)
for J in range(ROUND,1,-1):
print (PLAY[J],”:”,end=””)
(i) 20:10: (ii) 20:10:50: (iii) 20: (iv) 40:50:20:
Ans. (i) Maximum =3
Minimum =2
36. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable N. [SP 17]
import random
SIDES=[“EAST”,”WEST”,”NORTH”,”SOUTH”];
N=random.randint(1,3)
OUT=””
for I in range(N,1,-1):
OUT=OUT+SIDES[I]
print (OUT)
(i) SOUTHNORTH (ii) SOUTHNORTHWEST (iii) SOUTH (iv) EASTWESTNORTH
Ans. (i) SOUTHNORTH
Maximum value of N = 3
Minimum value of N = 1
37. Observe the following Python code and find out which out of the given options (i) to (iv) are the expected correct
output(s).Also assign the maximum and minimum value that can be assigned to the variable ‘Go’. 2 [SP 16]
import random
X =[100,75,10,125]
Go = random.randint(0,3)
for i in range(Go):
print (X[i],”$$”,end=””)
(i) 100$$75$$10$$ (ii) 75$$10$$125$$ (iii) 75$$10$$ (iv) 10$$125$$100
Ans. 100 $$ 75 $$ 10 $$
Minimum Value that can be assigned to Go is 0
Maximum Value that can be assigned to Go is 3
52 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
38. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable N.
import random
NAV = [“LEFT”,”FRONT”,”RIGHT”,”BACK”]
NUM = random.randint(1,3)
NAVG = “”
for C in range(NUM,1,-1):
NAVG = NAVG+NAV[C]
print (NAVG)
(i) BACKRIGHT (ii) BACKRIGHTFRONT (iii) BACK (iv) LEFTFRONTRIGHT
Ans. (i) BACKRIGHT Max value 3 and minimum value 1 for variable NUM
39. Observe the following program and answer the questions that follow: [SP 17]
import random
X=3
N=random.randint(1,X)
for i in range(N):
print (i,”#”,i+1)
(a) What is the minimum and maximum number of times the loop will execute?
(b) Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?
(i) 0#1 (ii) 1#2 (iii) 2#3 (iv) 3#4
Ans. (a) Minimum Number = 1
Maximum Number = 3
(b) Line (iv) is not expected to be a part of the output.
40. Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also, write
the maximum and the minimum values that can be assigned to the variable Y. 2 [SP 18]
import random
X=random.random()
Y=random.randint(0,4)
print (int(X),”:”,Y+int(X))
(i) 0: 0 (ii) 1:6 (iii) 2:4 (iv) 0:3
Ans. (i) and (iv) are the possible output(s)
Minimum value that can be assigned to Y = 0
Maximum value assigned to Y =4
41. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable PICK. 2 [D 16]
import random
PICK=random.randint(0,3)
CITY=[“DELHI”,”MUMBAI”,”CHENNAI”,”KOLKATA”]
for I in CITY:
for J in range(1,PICK):
print(I,end=””)
print()

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 53
(i) (ii)
DELHIDELHI DELHI
MUMBAIMUMBAI DELHIMUMBAI
CHENNAICHENNAI DELHIMUMBAICHENNAI
KOLKATAKOLKATA
(iii) (iv)
DELHI DELHI
MUMBAI MUMBAIMUMBAI
CHENNAI KOLKATAKOLKATAKOLKATA
KOLKATA
Ans. Options (i) and (iii) are possible.
PICK maxval=3 minval=0
42. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum
values that can be assigned to variable PICKER.
import random
PICKER=random.randint(0,3)
COLOR=[“BLUE”,”PINK”,”GREEN”,”RED”]
for I in COLOR:
for J in range(1,PICKER):
print(I,end=””)
print()

(i) (ii)
BLUE BLUE
PINK BLUEPINK
GREEN BLUEPINKGREEN BLUE
RED
(iii) (iv)
PINK BLUEBLUE
PINKGREEN PINKPINK
GREENRED GREENGREEN
REDRED
Ans. Options (i) and (iv) are possible.
PICKER maxval=3 minval=0
43. What possible outputs(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 that can be assigned to each of the variables BEGIN and
LAST. 2 [D 18]
import random
POINTS=[30,50,20,40,45];
BEGIN=random.randint(1,3)
LAST=random.randint(2,4)
for C in range(BEGIN,LAST+1):
print (POINTS[C],”#”,end=””)

(i) (ii) (iii) (iv)


20#50#30# 20#40#45# 50#20#40# 30#50#20#

54 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Ans. (ii) 20#40#45# and (iii) 50#20#40#
Max value for BEGIN 3
Max value for LAST 4
44. What possible output(s) are expected to be displayed on screen at the time of execution of the program from the
following Python code? Also specify the minimum values that can be assigned to each of the variables Start and
End. 2 [comptt 2019]
import random
VAL=[80,70,60,50,40,30,20,10]
Start=random.randint(1,3)
End=random.randint(Start,4)
for I in range(Start,End+1):
print (VAL[I],”*”,end=””)
(i) 40 * 30 * 20 * 10 * (ii) 70 * 60 * 50 * 40 * 30 *
(iii) 50 * 40 * 30 * (iv) 60 * 50 * 40 * 30 *
Ans. No output
Minimum value for Start: 1
Minimum value for End : 1
45. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from
the following code? Also specify the minimum values that can be assigned to each of the variables From and To.
2 [2019]
import random
VAL=[15,25,35,45,55,65,75,85];
From=random.randint(1,3)
To =random.randint(From,4)
for I in range(From,To+1):
print (VAL[I],”*”,)
(i) 35 * 45 * 55 * 65 * 75 * (ii) 35 * 45 * 55 *
(iii) 15 * 25 * 35 * 45 * (iv) 35 * 45 * 55 * 65 *
Ans. (ii) 35 * 45 * 55 *
Minimum value for From:1
Minimum value for To:1
46. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from
the following code? Also specify the minimum values that can be assigned to each of the variables BEGIN and
LAST. 2[2019]
import random
VALUES=[10,20,30,40,50,60,70,80];
BEGIN=random.randint(1,3)
LAST =random.randint(BEGIN,4)
for I in range(BEGIN,LAST+1):
print (VALUES[I],”-”,end=””)
(i) 30 - 40 - 50 - (ii) 10 - 20 - 30 - 40 -
(iii) 30 - 40 - 50 - 60 - (iv) 30 - 40 - 50 - 60 - 70 –
Ans. (i) 30-40-50-
Minimum value for BEGIN:1
Minimum value for LAST:1
Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 55
47. What possible outputs(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 that can be assigned to each of the variables FROM and
TO. 2 [SP 2019-20]
import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4) 2 3 4
for K in range(FROM,TO+1):
print (AR[K],end=”# “)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
Ans. (ii) 30#40#50# Maximum value FROM,TO is 3,4
48. What possible outputs(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 that can be assigned to each of the variables Lower and
Upper.
import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,3)
Upper =random.randint(2,4)
for K in range(Lower, Upper +1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#
Ans. OUTPUT: (ii)
Maximum value of Lower: 3
Maximum value of Upper: 4
49. What possible output(s) are expected to be displayed on screen at the time of exection of the program from
the following code? Also specify the minimum and maximum values that can be assigned to the variable End.
[comptt 2020]
import random
Colours=[“VIOLET”,”INDIGO”,”BLUE”,”GREEN”,”YELLOW”,”ORANGE”,”RED”]
End=random.randrange(2)+3
Begin=random.randrange(End)+1
for i in range(Begin,End):
print(Colours[i],end=’&’)

(i) INDIGO&BLUE&GREEN& (ii) VIOLET&INDIGO&BLUE&


(iii) BLUE&GREEN&YELLOW& (iv) GREEN&YELLOW&ORANGE&

Ans. (i) INDIGO&BLUE&GREEN&


Minimum Value of End = 3
Maximum Value of End = 4

56 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
OUTPUT : STRING
50. Observe the following Python code carefully and 52. Find and write the output of the following Python
obtain the output, which will appear on the screen code : 2 [comptt 19]
after execution of it. [SP 17] Str1=”EXAM2018”
def Findoutput(): Str2=””
L=”earn” I=0
x=” “ while I<len(Str1):
count=1 if Str1[I]>=”A” and Str1[I]<=”M”:
for i in L: Str2=Str2+Str1[I+1]
elif Str1[I]>=”0” and Str1[I]<=”9”:
if i in[‘a’,’e’,’i’,’o’,’u’]:
Str2=Str2+ (Str1[I-1])
  x=x+i.swapcase()
else:
else:
Str2=Str2+”*”
  if count%2!=0:
I=I+1
x=x+str(len(L[:count])) print (Str2)
else:
Ans. X*M2M201
  count =count +1
53. Give the output
print (x)
def makenew(mystr):
Findoutput()
newstr = “ “
Ans. EA11 count = 0
51. Give the output if input is “Hello 123” for i in mystr:
a=input(“enter string”) if count%2!=0:
s=”” newstr= newstr+str(count)
for i in a: elif i.islower():
if i.islower(): newstr=newstr+i.upper()
s=s+(i.upper()) else:
newstr=newstr+i
elif i.isupper():
count+=1
s=s+(i.lower())
newstr = newstr+mystr[:1]
elif i.isnumeric():
print (“The new string is :”,newstr)
s=s+str(int(i)+1)
makenew(“sTUdeNT”)
else: Ans. The new string is: S1U3E5Ts
s=s+”*”
54. Find and write the output of the following python
del(a) code: 2[2019]
a=s Text1=”AISSCE 2018”
print(“new value of str”,a) Text2=””
Ans. new value of str hELLO*234 I=0

ord(): The ord() function returns the number while I<len(Text1):
representing the unicode code of a specified character if Text1[I]>=”0” and Text1[I]<=”9”:
Val = int(Text1[I])
For example ord(‘B’) returns 66 which is a unicode
code point value of character ‘B’. Val = Val + 1
Text2=Text2 + str(Val)
A-Z 65-90
elif Text1[I]>=”A” and Text1[I] <=”Z”:
a-z 97-122 Text2=Text2 + (Text1[I+1])
chr(): The chr() function in Python accepts an integer else:
which is a unicode code point and converts it into a Text2=Text2 + “*”
string representing a character. I=I+1
print(chr(66))=B print (Text2)
Ans. ISSCE *3129

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 57
55. Find and write the output of the following python 58. Give the output
code: [2019] Mystring=”What@OUTPUT!”
Msg1=’WeLcOME’ str=’’ ’’
Msg2=’GUeSTs’ for i in range(len(Mystring)):
Msg3=’’ if not Mystring[i].isalpha():
for I in range(0,len(Msg2)+1): str=str+”*”
if Msg1[I]>=’A’ and Msg1[I]<=’M’:
elif Mystring[i].isupper():
Msg3=Msg3+Msg1[I]
val=ord(Mystring[i])

elif Msg1[I]>=’N’ and Msg1[I]<=’Z’:
val=val+1
Msg3=Msg3+Msg2[I]
str=str+chr(val)
else:
else:
Msg3=Msg3+’*’
str=str+Mystring[i+1]
print (Msg3)
print(str)
Ans. G*L*TME
Ans. Xat@*PVUQVU*
56. Give the output
Text=”Mind@Work!”
59. Give the output of the following program segment:
NAME = “IntRAneT”
T=””
N=””
c=0
for i in Text: for x in range(len(NAME)):

if not i.isalpha(): if NAME[x].islower():


T=T+”*” N=N+NAME[x].upper()
elif not i.isupper(): elif NAME[x].isupper():
T=T+(Text[c+1]) if x%2==0:
else: N=N+NAME[x].lower()
T=T+i.upper() else:
c=c+1 N= N+NAME[x - 1]
print(T) print(N)
Ans. Mnd@*Wrk!* Ans. iNTtaNEe
57. Give the output 60. Find the output of the following program :
Text=”Mind@Work!” def ChangeIt(Text,C):
T=”” T=””
c=0 for K in range(len(Text)):
for i in Text: if Text[K]>=’F’ and Text[K]<=’L’:
if not i.isalpha(): T=T+Text[K].lower();
T=T+”*” elif Text[K]==’E’ or Text[K]==’e’:
elif not i.isupper(): T=T+C;
T=T+(Text[c+1]) elif K%2==0:
else: T=T+Text[K].upper()
val=ord(i)
else:
val=val+1
T=T+T[K-1]
T=T+chr(val)
print(“New TEXT:”,T)
c=c+1
OldText=”pOwERALone”
print(T)
ChangeIt(OldText,”%”)
Ans. Nnd@*Xrk!*
Ans. New TEXT: PPW%RRllN%
58 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
61. Find the output of the following program: 64. Find the output of the following program :
def Mycode(Msg,C): def Change(Msg,L):
M=”” M=””
for i in range(len(Msg)): for Count in range(0,L,1):
if “B”<=Msg[i]<=”H”: if Msg [Count].isupper ():
M=M+Msg[i].lower();
M=M+Msg[Count].lower()
elif Msg[i]==”A” or Msg[i]==”a”:
elif Msg[Count].islower():
M=M+C;
elif i%2==0: M= M+Msg[Count].upper()
M=M+Msg[i].upper() elif Msg [Count].isdigit():
else: C=int(Msg[Count])
M=M+Msg[i-1] C=C+1
print(“New Line = “,M) M=M+str(C)
text=”ApaCHeSeRvEr”; else:
Mycode(text,”#”) M= M+”*”
Ans. New Line = #A#chHSSRReE
print(M)
62. Find the output of the following program : Message = “2005 Tests ahead”
def Encode(Info,N):
Size=len(Message)
In=””
Change(Message,Size)
for I in range(len(Info)):
if I%2==0: Ans. 3116*tESTS*AHEAD
v=ord(Info[I]) 65. Find the output of the following program :
v=v-N def Secret(Msg,N):
In=In+chr(v) Mg=””
elif Info[I].islower(): for c in range(len(Msg)):
In=In+Info[I].upper() if c%2==0:
else:
v=ord(Msg[c])
v=ord(Info[I])
v=v+N
v=v+N
Mg=Mg+chr(v)
In=In+chr(v)
print(In) elif Msg[c].isupper():
Memo=”Justnow” Mg = Mg+Msg[c].lower()
Encode(Memo,2) else:
Ans. HUqTlOu v=ord(Msg[c])
63. Find the output of the following program [d 05] v=v-N
def Convert(Str,L): Mg=Mg+chr(v)
S=”” print(Mg)
for Count in range(len(Str)): SMS = “rEPorTmE”
if Str [Count].isupper(): Secret(SMS,2)
S= S+Str[Count].lower() Ans. teRmttoe
elif Str [Count].islower():
S=S+Str[Count].upper() 66. Give the output of the following program
elif Str [Count].isdigit (): Name=”a ProFile”
S=S+str(int(Str[Count]) + 1) N=””
else: for x in range(0,len(Name),1):
S=S+”*” if Name[x].islower():
print(S) N=N+Name[x].upper()
Text= “CBSE Exam 2021” elif Name[x].isupper():
Size=len(Text) if x%2!=0:
Convert(Text,Size); N=N+Name[x-1].lower()
Ans. cbse*eXAM*3132
Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 59
else: p=p+s[i]
n=ord(Name[x]) print(“Changed String”,p)
n=n-1 str=”SUCCESS”
N=N+chr(n) print(“Original String”,str)
Name=N repch(str);
print(Name) Ans. Original String SUCCESS
Ans. AOROoILE Hello
67. Give the output [SP 21] Changed String SU!CE@
def Display(str): 70. Find the output of the following program :
m=”” def MIXITNOW(S):
for i in range(0,len(str)): WS=””
if(str[i].isupper()): for I in range(0,len(S)-1,2):
m=m+str[i].lower()
WS=WS+S[I+1]
elif str[i].islower():
WS=WS+S[I]
m=m+str[i].upper()
S=WS
else:
if i%2==0: print(S)
m=m+str[i-1] WS=””
else: for I in range(0,len(S)):
m=m+”#” if S[I]>=”M” and S[I]<=”U”:
print(m) WS=WS+”@”;
Display(‘[email protected]’) else:
Ans. fUN#pYTHONn#. WS=WS+S[I-1:I]
68. Give the output 2 [SP 2019-20] print(WS)
def fun(s): Word=”CRACKAJACK”;
k=len(s) MIXITNOW(Word);
m=” “ Ans. RCCAAKAJKC
for i in range(0,k): @RCCAAKAJK
if(s[i].isupper()): 71. Find the output of the following program :
m=m+s[i].lower() def JumbleUp(T):
elif s[i].isalpha(): CT=””
m=m+s[i].upper() L=len(T)
else: for C in range(0,L,2):
m=m+’bb’ CT=CT+T[C+1]
print(m) CT=CT+T[C]
fun(‘school2@com’) T=CT
CT=””
Ans. SCHOOLbbbbCOM
print(T)
69. Give the output for C in range(1,len(T),2):
def repch(s): if “U”>=T[C]>=”M”:
p=”” #if T[C]>=”M” and T[C]<=”U”:
for i in range(len(s)-1): CT=CT+”@”
if i%2!=0 and s[i]==s[i+1]: else:
p=p+”@” CT=CT+T[C-1:C+1]
print(“Hello”) print(CT)
elif s[i]= =s[i+1]: Str=”HARMONIOUS”
JumbleUp(Str)
p=p+”!”
else: Ans. AHMRNOOISU
AH@@OI@
60 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
72. Find the output of the following program : W=W+Big(WX[i],WX[i+1])
def Big(A,B): W=W+WX[L-1]
if (A>B): print(W)
return chr(ord(A)+1) Ans. zyom
else:
73. Give the output
return chr(ord(B)+2) a=”Hello”
WX=”Exam” L=list(a)
W=”” a=’’.join(reversed(L))
L=len(WX) print(a)
for i in range(0,L-1,1):
Ans. olle

Output : Global Variable


74. What do you understand by local and global scope Inside add() : 12
of variables? How can you access a global variable In main: 15
inside the function, if function has a variable with Note: In case you have a local variable with the same
same name. [SP 2019-20] name, use the globals() function to access global
variable.
Ans. A global variable is a variable that is accessible globals()[‘your_global_var’]
globally. A local variable is one that is only accessible for ex:
to the current scope, such as temporary variables
y=globals()[‘a’]
used in a single function definition.
A variable declared outside of the function or in 76. Give the output
global scope is known as global variable. def fun():
This means, global variable can be accessed inside print(a)
or outside of the function where as local variable can a=5
be used only inside of the function. We can access fun()
by declaring variable as global A. print(a)
75. Explain the use of global key word used in a function Ans. 5
with the help of a suitable example. [SP 21] 5
Ans. Use of global key word: In Python, global keyword 77. Give the output
allows the programmer to modify the variable outside
the current scope. It is used to create a global variable
def fun():
and make changes to the variable in local context. a=10
A variable declared inside a function is by default print(a)
local and a variable declared outside the function a=5
is global by default. The keyword global is written fun()
inside the function to use its global value. Outside print(a)
the function, global keyword has no effect. Ans. 10
Example: 5
c = 10 # global variable
78. Give the output
def add():
def fun():
global c
global a
c = c + 2
a=10
# global value of c is incremented
print(a)
by 2
a=5
print(“Inside add():”, c)
fun()
add()
print(a)
c=15
print(“In main:”, c)
Ans. 10
output: 10

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 61
79. Give the output 83. Find and write the output of the following python
def fun(): code: [SP 2019-20]
a=20 a=10
print(a) def call():
def fun2(): global a
global a
a=15
a=30
print(a) b=20
a=10 print(a)
fun() call()
print(a) Ans. 15
fun2()
84. Write the output of the following Python code:
print(a)
[1][comptt 2020]
Ans. OUTPUT def Update(X=10):
20 X += 15
10 print( ‘X = ‘, X)
30
X=20
30
Update()
80. Give the output print( ‘X = ‘, X)
def fun(a):
Ans. X = 25
a=10
X = 20
print(a)
a=5 85. Give the output
fun(a) def fun():
print(a) a=10
Ans. 10 y=globals()[‘a’]
5 print(“inside”,a)
81. Give the output print(“y=”,y)
def fun(): a=5
   global a fun()
a=10 print(“outside”,a)
y=a Ans. inside 10
print(“inside”,a)
y=5
print(“y=”,y)
outside 5
a=5
fun() 86. Give the output
print(“outside”,a) def func(x,y=2):
Ans. inside 10 g=5
y=10 x=x-y;
outside 10 g=g*10;
82. Give the output print(x,y,g)
def fun(): g=7
a=10 h=10
y=a func(g,h)
print(“inside”,a)
print(g,h)
print(“y=”,y)
func(g)
a=5
fun() print(g,h)
print(“outside”,a) Ans. -3 10 50
Ans. inside 10 7 10
y=10 5 2 50
outside 5 7 10
62 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
87. Give the output demo(a,b)
g=10 print(a,b)
def func(x,y=10): demo(a,b)
x=x-y Ans. 3 8 13
y=x*10 8 5
z=x+y+g 8 13 18
return z 89. Give the output
g=func(g,15) def pa(a,b,c):
print(g) x=4;
g=func(g) c+=x;
print(g) c*=globals()[‘x’]
Ans. -45 b+=c;
-650 return a,b,c
88. Give the output y=1
a=3 x=2
def demo(x,y): z=5
global a x,y,z=pa(y,x,z)
a=x+y print(x,y,z)
z=a+y y,z,x=pa(z,y,x)
y+=x print(x,y,z)
print(x,y,z) Ans. 1 20 18
b=5 5 18 25

Functions/Methods/Modules Name
Math Module
Function Description
ceil(x) Returns the smallest integer greater than or equal to x.
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
isnan(x) Returns True if x is a NaN
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
cos(x) Returns the cosine of x
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
pi Mathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159...)
e Mathematical constant e (2.71828...

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 63
random module

randint() random() randrange() uniform()
pickle module
dump() load()
csv module
Dictreadwe() DictWriter() reader() writer()
Matplotlib.pyplot
axes() ba() bath() plot() pie()
show() title() xlabel() ylabel()
statistics module
mean() median model()

90. Name the Python Library modules which need to be imported to invoke the following functions: [D 17]
(i) ceil() (ii) randint()
Ans. (i) math (ii) random
91. Observe the following Python functions and write the name(s) of the module(s) to which they belong:
(i) uniform() (ii) findall() 1 [SP 16]
Ans. (i) random (ii) re
92. Name the Python Library modules which need to be imported to invoke the following functions:
(i) ceil() (ii) randint()  
Ans. (i) math (ii) random
93. Name the Python Library modules which need to be imported to invoke the following functions
(i) floor() (ii) randint() 1 [OD 17]
Ans. (i) math (ii) random
94. Identify and write the name of the module to which the following functions belong:
(i) ceil( ) (ii) findall() 1 [SP 18]
Ans. (i) ceil( ) - math module (ii) findall( ) – re module
95. Name the Python Library modules which need to be imported to invoke the following functions
(i) load() (ii) pow() 1 [D 16]
Ans. (i) pickle (ii) math
96. Name the Python Library modules which need to be imported to invoke the following functions (i) sqrt() (ii)
dump() 1 [OD 16]
Ans. (i) math (ii) pickle
97. Name the Python Library modules which need to be imported to invoke the following functions: 1 [D 18]
(i) sin() (ii) search()
Ans. (i) math (ii) re
98. Name the function/method required to (i) check if a string contains only uppercase letters and (ii) gives the total
length of the list. 1 [D 15]
Ans. (i) isupper() (ii) len()
99. Name the function/method required to (i) check if a string contains only alphabets and (ii) give the total length
of the list. 1 [OD 15]
Ans. isalpha() len()

64 Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
100. Name the Python Library modules which need to be imported to invoke the following functions : 1 [comptt 2019]
(i) open() (ii) factorial()
Ans. (i) os (ii) math
101. Name the Python Library modules which need to be imported to invoke the following functions: 1[2019]
(i) search() (ii) date()
Ans. (i) re (ii) datetime
102. Name the Python Library modules which need to be imported to invoke the following functions: 1 [2019]
(i) sqrt() (ii) start ()
Ans. (i) math (ii) re
103. Name the Python Library modules which need to be imported to invoke the following functions: 1 [comptt 2020]
(i) cos() (ii) randint()
Ans. (i) math (ii) random
104. Name the Python Library modules which need to be imported to invoke the following functions: [1][comptt 2020]
(i) floor() (ii) random()
Ans. (i) math (ii) random
105. Name the Python Library modules which need to be imported to invoke the following functions:
(i) sin( ) (ii) randint ( ) 1[SP 2020]
Ans. (i) math (ii) random
106. Name the built-in mathematical function/method that is used to return an absolute value of a number.
1[SP 21]
Ans. abs()

Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I) 65

You might also like