Functions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

Name the Python Library modules which need to be imported to invoke the following functions :

1. load ()
2. pow () [CBSE Delhi 2016]

Answer:

1. pickle
2. math

Question 2.
Name the modules to which the following func-tions belong:

1. Uniform ()
2. fabs () [CBSE SQP 2016]

Answer:

1. random ()
2. math ()

Question 3.
Differentiate between the round() and floor() functions with the help of suitable example.
[CBSE Comptt. 2016]
Answer:
The function round() is used to convert a fractional number into whole as the nearest next whereas the function
floor() is used convert to the nearest lower whole number, e.g.,
round (5.8) = 6, round (4.1) = 5 and floor (6.9) = 6, floor (5.01) = 5

Short Answer Type Questions (2 marks):

Question 1.
Out of the following, find those identifiers, which cannot be used for naming Variables or functions in a Python
program:
Total * Tax, While, Class, Switch, 3rd Row, finally, Column 31, Total. [CBSE Outside Delhi-2016]
Answer:
Total * Tax, class, 3rd Row, finally

Question 2.
Name the Python Library modules which need to be imported to invoke the follwing functions :

1. sqrt()
2. dump() (CBSE Outside Delhi-2016)

Answer:

1. math
2. pickle

Question 3.
Out of the following, find the identifiers, which cannot be used for naming Variable or Functions in a Python
program: [CBSE Delhi 2016]
_Cost, Price*Qty, float, switch, Address one, Delete, Number12, do
Answer:
Price *Qty, float, Address one, do

Question 4.
Out of the following find those identifiers, which can not be used for naming Variable or Functions in a Python
Program:
Days * Rent, For, A_price, Grand Total, do, 2Clients, Participantl, My city
Answer:
Illegal variables or functions name are as below: Days * Rent, do, 2Clients, For and Grant Total Because of
being either keyword or including space or operator or starting with integar.

Question 5.
Name the function / method required for [CBSE SQP 2015]

1. Finding second occurrence of m in madam.


2. get the position of an item in the list.

Answer:

1. find
2. index

Question 6.
Which string method is used to implement the following:

1. To count the number of characters in the string.


2. To change the first character of the string in capital letter.
3. To check whether given character is letter or a number.
4. To change lowercase to uppercase letter.
5. Change one character into another character. [CBSE TextBook]

Answer:

1. len(str)
2. str.capitalize()
3. ch.isalnum()
4. str.upper()
5. str.replace(old,new)

Question 7.
What is the difference between input() and raw_input()?
Answer:
raw_input() takes the input as a string whereas input() basically looks at what the user enters, and automatically
determines the correct type. We use the inputQ function when you are expecting an integer from the end-user,
and raw_input when you are expecting a string.

Question 8.
What are the two ways of output using print()?
Answer:
Ordinarily, each print statement produces one line of output. You can end the print statement with a trailing ’ to
combine the results of multiple print statements into a single line.
Question 9.
Why does the expression 2 + 3*4 result in the value 14 and not the value 24?
Answer:
Operator precedence rules* make the expression to be interpreted as 2 + (3*4) hence the result is 14.

Question 10.
How many times will Python execute the code inside the following while loop? You should answer the question
without using the interpreter! Justify your answers.

i = 0
while i < 0 and i > 2 :
print “Hello ...”
i = i+1

Answer:
0 times.

Question 11.
How many times will Python execute the code inside the following while loop?

i = 1
while i < 10000 and i > 0 and 1:
print “ Hello ...”
i = 2 * i

Answer:
14.

Question 12.
Convert the following for loop into while loop, for i in range (1,100):

if i % 4 == 2 :
print i, “mod”, 4 , “= 2”

Answer:

i=1
while i < 100:
if i % 4 == 2:
print i, “mod”, 4 , “= 2”
i = i +1

Question 13.
Convert the following for loop into while loop.

for i in range(10):
for j in range(i):
print '$',
print"

Answer:

i=0
while i < 10:
j=0
while j < i:
print '$’
print"
Question 14.
Rewrite the following for loop into while loop: [CBSE Text Book]

for a in range(25,500,25):
print a

Answer:

a=25
while a < 500:
print a
a = a + 25

Question 15.
Rewrite the following for loop into while loop: [CBSE Text Book]

for a in range(90, 9, -9):


print a

Answer:

a = 90
while a > 9:
print a
a = a-9

Question 16.
Convert the following while loop into for loop:

i = 0
while i < 100:
if i % 2 == 0:
print i, “is even”
else:
print i, “is odd”
i = i + 1

Answer:

for i in range(100):
if i % 2 == 0:
print i, “is even”
else :
print i, “is odd”

Question 17.
Convert the following while loop into for loop

char = ""
print “Press Tab Enter to stop ...”
iteration = 0
while not char == “\t” and not iteration > 99:
print “Continue?”
char = raw_input()
iteration+ = 1

Answer:

char = ""
print “Press Tab Enter to stop ...”
for iteration in range(99):
if not char == ‘\t’:
print “Continue?”
char = raw_input()

Question 18.
Rewrite the following while loop into for loop:

i = 10
while i<250:
print i
i = i+50

Answer:

for i in range(10, 250, 50):


print i

Question 19.
Rewrite the following while loop into for loop:

i=88
while(i>=8): print i
i- = 8

Answer:

for i in range(88, 9, -8)


print i

Question 20.
Write for statement to print the series 10,20,30, ……., 300
Answer:

for i in range(10, 301, 10):


print i

Question 21.
Write for statement to print the series 105,98,91,… .7
Answer:

for i in range(105, 8, -7):


print i

Question 22.
Write the while loop to print the series: 5,10,15,…100
Answer:

i=5
while i <= 100:
print i
i = i + 5

Question 23.
How many times is the following loop executed? [CBSE Text Book]
for a in range(100,10,-10):
print a
Answer:
9 times.

Question 24.
How many times is the following loop executed? [CBSE Text Book]

i = 100
while (i<=200):
print i
i + =20

Answer:
6 times

Question 25.
State whether the statement is True or False? No matter the underlying data type if values are equal returns true,

char ch1, ch2;


if (ch1==ch2)
print “Equal”

Answer:
True. Two values of same data types can be equal.

Question 26.
What are the logical operators of Python?
Answer:
or, and, not

Question 27.
What is the difference between ‘/’ and ‘//’ ?
Answer:

// is Integer or Floor division whereas / is normal division


(eg) 7.0 // 2 → 3.0
7.0/2 → 3.5

Question 28.
How can we import a module in Python?
Answer:
1. using import

Syntax:
import[,,...]
Example:
import math, cmath

2. using from

Syntax:
fromimport[, ,.. ,]
Example: .
from fib. import fib, fib2.

Question 29.
What is the difference between parameters and arguments?
Answer:
S.No. Parameters Arguments
Values provided in Values provided in
1
function header function call.
(eg) def main() radius
(eg) def area (r): = 5.0 area (radius)
2
—> r is the parameter —> radius is the
argument

Question 30.
What are default arguments?
Answer:
Python allowes function arguments to have default values; if the function is called without the argument, the
argument gets its default value

Question 31.
What are keyword arguments?
Answer:
If there is a function with many parameters and we want to specify only some of them in function call,
then value for such parameters can be provided by using their names instead of the positions. These are called
keyword argument.

(eg) def simpleinterest(p, n=2, r=0.6)


' def simpleinterest(p, r=0.2, n=3)

Question 32.
What are the advantages of keyword arguments?
Answer:
It is easier to use since we need not remember the order of the arguments.
We can specify the values for only those parameters which we want, and others have default values.

Question 33.
What does “in” do?
Answer:
“in” is a membership operator. It evaluates to true if it finds a variable/string in the specified sequence :
Otherwise i+evaluates to false.

(eg) S = “Hello World"


if “Hell” in S:
print “True”
will print True.

Question 34.
What does “not in” do?
Answer:
“not in” is a membership operator. It evaluates to true if it does not finds a variable/string
in the specified sequence. Otherwise it evaluates to false,

(eg) S = “Hello World”


if “Hell” not in S:
print “False”
will print False.

Question 35.
What does “slice” do?
Answer:
The slice[n:m] operator extracts subparts from a string. It doesn’t include the character at index m.

(eg) S = “Hello World”


print s[0:4] → Hell

Question 36.
What is the use of negative indices in slicing?
Answer:
Python counts from the end (right) if negative indices are given.

(eg) S = “Hello”
print S[:-3] >> He
print S[-3:] >> llo

Question 37.
Explain find() function?
Answer:
find (sub[,start[,end]])
This function is used to search the first occurrence of the substring in the given string.
It returns the index at which the substring starts. It returns -1 if the substring doesn’t occur in the string.

(eg) str = “computer” -


str.findf("om”) → 1

Question 38.
What are the differences between arrays and lists?
Answer:
An array holds fixed number of values. List is of variable-length – elements can be dynamically added or
removed
An array holds values of a single type. List in Python can hold values of mixed data type.

Question 39.
What is the difference between a tuple and a list?
Answer:
A tuple is immutable whereas a list is a mutable.
A tuple cannot be changed whereas a list can be changed internally.
A tuple uses parenthess (()) whereas a list uses square brackets ([]).
tuple initialization: a = (2, 4, 5)
list initialization: a = [2, 4, 5]

Question 40.
Carefully observe the following python code and answer the question that follows:
x=5
def func2():
x=3
global x
x=x+1
print x
print x
On execution the above code produces the following output.
6
3
Explain the output with respect to the scope of the variables.
Answer:
Names declared with global keyword have to be referred at the file level. This is because the global scope.
If no global statement is being used the variable with the local scope is accessed.
Hence, in the above code the statement succeeding the statement global x informs Python to increment
the global variable x
Hence, the output is 6 i.e. 5 + 1 which is also the value for global x.
When x is reassingned with the value 3 the local x hides the global x and hence 3 printed.
(2 marks for explaning the output) (Only 1 mark for explaining global and local namespace.)

Question 41.
Explain the two strategies employed by Python for memory allocation. [CBSE SQP 2016]
Answer:
Pythonuses two strategies for memory allocation-
(i) Reference counting
(ii) Automatic garbage collection
Reference Counting: works by counting the number of times an object is referenced by other in the system.
When an object’s reference count reaches zero, Python collects it automatically.
Automatic Garbage Collection: Python schedules garbage collection based upon a threshold of object allocations
and object deallocations. When the number of allocations minus the number of deallocations are greater that the
threshold number, the garbage collector is run and the unused blocks of memory is reclaimed.

TOPIC – 2
Writing Python Programs

Question 1.
Rewrite the following code in Python after removing all syntax errors(s). Underline each correction done in the
code. [CBSE Delhi-2016]
for Name in [Amar, Shveta, Parag]
if Name [0] = ‘s’:
Print (Name)
Answer:

for Name in [“_Amar”, ”_Shveta_” , "_Parag_”] :


if Name [0] E == ‘S’ :
Print (Name)

Question 2.
Rewrite the following code is Python after removing all syntax errors(s).
Underline each correction done in the code. [CBSE Outside Delhi-2016]
for Name in [Ramesh, Suraj, Priya]
if Name [0] = ‘S’:
Print (Name)
Answer:

for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”]


if Name [0] =_=‘S’ :
print (Name)

Question 3.
What will be the output of the following python code considering the following set of inputs?
AMAR
THREE
A123
1200
Also, explain the try and except used in the code.
Start = 0
while True :
Try:
Number = int (raw input (“Enter Number”))
break
except valueError : start=start+2
print (“Re-enter an integer”)
Print (start)
Answer:
Output:

Enter Number AMAR


Re-enter an integer
Enter Number THREE
Re-enter an integer
Enter Number A123
Re-enter an integer
Enter Number 12006

Explanation : The code inside try makes sure that the valid number is entered by the user.
When any input other an integer is entered, a value error is thrown and it prompts the user to enter another value.

Question 4.
Give the output of following with justification. [CBSE SQP 2015]

x = 3
x+ = x-x
print x

Answer:
Output: 3
Working:

x = 3
x = (x+ x-x ):x = 3 + 3 - 3 = 3

Question 5.
What will be printed, when following Python code is executed? [CBSE SQP 2015]

class person:
def init (self,id):
self.id = id arjun = person(150)
arjun. diet [‘age’] = 50
print arjun.age + len(arjun. diet )

Justify your answer.


Answer:
52
arjun.age = 50
arjun.dict has 2 attributes so length of it is 2. So total = 52.

Question 6.
What would be the output of the following code snippets?
print 4+9
print “4+9”
Answer:
13 (addition), 49 (concatenation).
Question 7.
Highlight the literals in the following program
and also predict the output. Mention the types of
variables in the program.

a=3
b='1'
c=a-2
d=a-c
e=“Kathy”
f=‘went to party.’
g=‘with Sathy’
print a,g,e,f,a,g,“,”,d,g,“,”,c,g,“and his”,e,f

Answer:
a, c,d = integer
b, e,f,g = string
Output: 3 with Sathy Kathy, went to party. 3 with Sathy, 2 with Sathy , 1 with Sathy and his Kathy, went to
party.

Question 8.
What is the result of 4+4/2+2?
Answer:
4 + (4/2) + 2 = 8.

Question 9.
Write the output from the following code: [CBSE Text Book]

x= 10
y = 20
if (x>y):
print x+y
else:
print x-y

Answer:
– 10

Question 10.
Write the output of the following code:
print “Python is an \n interpreted \t Language”
Answer:
Python is an interpreted Language

Question 11.
Write the output from the following code:

s = 0
for I in range(10,2,-2):
s+=I
print “sum= ",s

Answer:
sum= 28

Question 12.
Write the output from the following code: [CBSE TextBook]
n = 50
i = 5
s = 0
while i<n:
s+ = i
i+ = 10
print “i=”,i
print “sum=”,s

Answer:

i= 15
i= 25
i= 35
i= 45
i= 55
sum= 125

Question 13.
Write the output from the following code: [CBSE TextBook]

n = 50
i = 5
s = 0
while i<n:
s+ = i
i+ = 10
print “i=”,i
print “sum=”,s

Answer:

i= 15
i= 25
i= 35
i= 45
i= 55
sum= 125

Question 14.
Observe the following program and answer the question that follows:
import random
x=3
N = random, randint (1, x)
for 1 in range (N):
print 1, ‘#’, 1 + 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
Answer:
a. Minimum Number = 1
Maximum number = 3
b. Line iv is not expected to be a part of the output.
Question 15.
Observe the following Python code carefully and obtain the output, which will appear on the screen after
execution of it. [CBSE SQP 2016]

def Findoutput ():


L = "earn"
X = " "
count = 1
for i in L:
if i in ['a', 'e',' i', 'o', 'u']:
x = x + 1. Swapcase ()
else:
if (count % 2 ! = 0):
x = x + str (len (L[:count]))
else:
x = x + 1
count = count + 1
print x
Findoutput ()

Answer:
EA3n

Question 16.
Find and write the output of the following Python code:

Number = [9,18,27,36] for N in Numbers:


print (N, "#", end = " ")
print ()

Answer:

Element Stack of operators Postfix Expression


1# 0 0
1# (1#) (1#)
2# (1#) (1#2#)
1# (2#) (1#2#3#)
2# (1#) 1#
3# (2#) 1#2#
(3#) 1#2#3#

Question 17.
What are the possible outcome(s) executed from the following code? Also,
specify the maximum and import random. [CBSE Delhi 2016]

PICK=random.randint (0,3)
CITY= ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"];
for I in CITY :
for J in range (1, PICK)
print (I, end = " ")
Print ()
(i) (ii)
DELHIDELHI DELHI
MUMBAIMUMBAI DELHIMUMBAI
CHENNAICHENNAI DELHIMUMBAICEHNNAI
KOLKATAKOLKATA
(iii) (iv)
DELHI DELHI
MUMBAI MUMBAIMUMBAI
CHENNAI KOLKATAKOLKATAKOLKATA
KOLKATA

Answer:
Option (i) and (iii) are possible option (i) only
PICKER maxval = 3 minval = 0

Question 18.
Find and write the output of the following Python code : [CBSE Outside Delhi-2016]

Values = [10,20,30,40]
for val in Values:
for I in range (1, Val%9):
print (I," * ", end= " ")
print ()

Answer:

Element Stack of operators Postfix Expression


1* 0 0
1* (1.*) (1*)
2* 0 (1*2*)
1* (1,*) (1*2*3*)
2* (2.*) 1*
3* 0 1*2*
(1.*) 1*2*3*
(2,* )
(3,* )

Question 19.
Write the output from the following code:

y = 2000
if (y%4==0):
print “Leap Year”
else:
print “Not leap year”

Answer:
Leap Year.

Question 20.
What does the following print?

for i in range (1,10):


for j in'range (1,10):
print i * j,
print
Answer:
123456789
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81

Question 21.
What will be the output of the following statement? Also, justify the answer.

>> print ‘Radhsa’s dress is pretty’.

Answer:
SyntaxError: invalid syntax.
The single quote needs to be replaced by V to get the expected output.

Question 22.
Give the output of the following statements :

>>> str=‘Honesty is the best policy’


>>> str.replace(‘o’,‘*’)

Answer:
‘H*nesty is the best p*licy’.

Question 23.
Give the output of the following statements :

>> str=‘Hello Python’


>>> str.istitle()

Answer:
True.

Question 24.
Give the output of the following statements:

>> str=‘Hello Python’


>>> print str.lstrip(“Hel”)

Answer:
Hello Python

Question 25.
Write the output for the following codes:

A={10:1000,20:2000,30:3000,40:4000,50:5000}
print A.items()
print A.keys()
print A.values()
Answer:
[(40,4000), (10,1000), (20,2000), (50,5000), (30,3000)] [40,10, 20, 50, 30] [4000,1000, 2000, 5000, 3000]

Question 26.
Write the output from the following code:

t=(10,20,30,40,50)
print len(t)

Answer:
5

Question 27.
Write the output from the following code:

t=(‘a’,‘b’,‘c’,‘A’,‘B’)
print max(t)
print min(t)

Answer:
‘c’
A’

Question 28.
Find the output from the following code:

T=(10,30,2,50,5,6,100,65)
print max(T)
print min(T)

Answer:
100
2

Question 29.
Write the output from the following code:

T1=(10,20,30,40,50)
T2 =(10,20,30,40,50)
T3 =(100,200,300)
cmp(T1, T2)
cmp(T2,T3)
cmp(T3,T1)

Answer:
0
-1
1

Question 30.
Write the output from the following code:

T1=(10,20,30,40,50)
T2=(100,200,300)
T3=T1+T2
print T3
Answer:
(10,20,30,40,50,100,200,300)

Question 31.
Find the output from the following code:

t=tuple()
t = t +(‘Python’,)
print t
print len(t)
t1=(10,20,30)
print len(t1)

Answer:
(‘Python’,)
1
3

Question 32.
Rewrite the following code in Python after remo¬ving all syntax error(s).
Underline each correction done in the code.

for student in [Jaya, Priya, Gagan]


If Student [0] = ‘S’:
print (student)

Answer:
for studednt in values [“Jaya”, “Priya”, “Gagan”]:
if student [0] = = “S”
print (student)

Question 33.
Find and write the output of the following Python code:

Values = [11, 22, 33, 44] for V in Values:


for NV in range (1, V%10):
print (NV, V)

Answer:
1, 11
2,22
3,33
4, 44

Question 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 SEL.

import random
SEL=random. randint (0, 3)
ANIMAL = [“DEER”, “Monkey”, “COW”, “Kangaroo”];
for A in ANIMAL:
for AAin range (1, SEL):
print (A, end =“”)
print ()
(i) (ii) (iii) (iv)
DEERDEER DEER DEER DEER
MONKEYMONKEY DELHIMONKEY MONKEY MONKEYMONKEY
COWCOW DELHIMONKEYCOW COW KANGAROOKANGAROOKANGAROO
KANGAROOKANGAROO KANGAROO

Answer:
Maximum value of SEL is 3.
The possible output is below
DEER
Monkey Monkey
Kangaroo Kangaroo Kangaroo
Thus (iv) is the correct option.

TOPIC-3
Random Functions

Question 1.
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. [CBSE Outside Delhi-2016]

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) (iii)  (iv)
BLUE BLUE PINK SLUEBLUE
PINK BLUEPINK PINKGREEN PINKPINK
GREEN BLUEPINKGREEN GREENRED GREENGREEN
RED BLUEPINKGREENRED REDRED

Answer:
Option (i) and (iv) are possible
OR
option (i) only
PICKER maxval = 3 minval = 0

Question 2.
What are the possible outcome(s) expected from the following python code? Also specify
maximum and minimum value, which we can have. [CBSE SQP 2015]

def main():
p = ‘MY PROGRAM’
i = 0
while p[i] != ‘R’:
l = random.randint(0,3) + 5
print p[l],’-’,
i += 1

(i) R – P – O – R –
(ii) P – O – R – Y –
(iii) O -R – A – G –
(iv) A- G – R – M –
Answer:
Minimum value=5
Maximum value=8
So the only possible values are O, G, R, A
Only option (iii) is possible.

TOPIC-4
Correcting The Errors

Question 1.
Rewrite the following Python code after removing all syntax error(s). Underline the corrections done.
[CBSE SQP 2015]

def main():
r = raw-input(‘enter any radius : ’)
a = pi * math.pow(r,2)
print “ Area = ” + a

Answer:

def main ():


r = raw_input(‘enter any radius : ’)
a = pi * math.pow(r,2)
print “ Area = ”, a

Question 2.
Rectify the error (if any) in the given statements.

>> str=“Hello Python”


>>> str[6]=‘S’

Answer:

str[6] = ‘S’ is incorrect ‘str’ object does not support item assignment.
str.replace(str[6],‘S’).

Question 3.
Find the errors from the following code:
T=[a,b,c]
print T
Answer:
NameError: name ‘a’ is not defined .
T=[‘a’,‘b’,‘c’]

Question 4.
Find the errors from the following code:
for i in 1 to 100:
print I
Answer:
for i in range (1,100):
print i

Question 5.
Find the errors from the following code:
i=10 ;
while [i<=n]:
print i
i+=10

Answer:

i=10
n=100
while (i<=n):
print i
i+=10

Question 6.
Find the errors from the following code:

if (a>b)
print a:
else if (a<b)
print b:
else
print “both are equal”

Answer:

if (a>b) // missing colon


print a:
else if (a<b) // missing colon // should be elif
print b:
else // missing colon
print “both are equal"

Question 7.
Find errors from the following codes:

c=dict()
n=input(Enter total number)
i=1
while i<=n:
a=raw_input(“enter place”)
b=raw_input(“enter number”)
c[a]=b
i=i+1
print “place”,“\t”,“number”
for i in c:
print i,“\t”,c[a[i]]

Answer:

c=dict()
n=input(‘‘Enter total number”)
i=1
while i<=n :
a=raw_input(“enter place”)
b=raw_inputf enter number”)
c[a]=b
i=i+1
print “place”,“\t”,“number”
for i in c:
print i,“\t”,c[i]
Question 8.
Observe the following class definition and answer the question that follows : [CBSE SQP 2016]

class info:
ips=0
def _str_(self): #Function 1
return "Welcome to the Info Systems"
def _init_(Self):
self. _ Sstemdate= " "
self. SystemTime = " "
def getinput (self):
self . Systemdate = raw_input ("enter data")
self , SystemTime = raw_Input ("enter data")
Info, incrips ()
Estaiomethod # Statement 1
def incrips ():
Info, ips, "times"
I = Info ()
I. getinput ()
Print I. SystemTime
Print I. _Systemdate # Statement 2

i. Write statement to invoke Function 1.


ii. On Executing the above code, Statement 2 is giving an error explain.
Answer:
i. print I
ii. The statement 2 is giving an error because _ Systemdate is a private variable and hence cannot to be printed
outside the class.

TOPIC – 5
Short Programs

Question 1.
Write a program to calculate the area of a rectangle. The program should get the length and breadth ;
values from the user and print the area.
Answer:

length = input(“Enter length”)


breadth = input(“Enter breadth”)
print “Area of rectangle =”,length*breadth

Question 2.
Write a program to calculate the roots of a quadratic equation.
Answer:

import math
a = input(“Enter co-efficient of x^2”)
b = input(“Enter co-efficient of x”)
c = inputfEnter constant term”)
d = b*b - 4*a*c
if d == 0:
print “Roots are real and equal”
root1 = root2 = -b / (2*a)
elif d > 0:
print “Roots are real and distinct”
root1 = (- b + math.sqrt(d)) / (2*a)
root2 = (-b - math.sqrt(d)) / (2*a)
else:
print “Roots are imaginary”
print “Roots of the quadratic equation are”,root1,“and”,root2
Question 3.
Write a program to input any number and to print all the factors of that number.
Answer:

n = inputfEnter the number")


for i in range(2,n):
if n%i == 0:
print i,“is a factor of’.n

Question 4.
Write a program to input ,.any number and to check whether given number is Armstrong or not.
(Armstrong 1,153,etc. 13 =1, 13+53 +33 =153)
Answer:

n = inputfEnter the number”)


savedn = n
sum=0
while n > 0:
a = n%10
sum = sum + a*a*a
n = n/10
if savedn == sum:
print savedn,“is an Armstrong Number”
else:
print savedn,”is not an Armstrong Number”

Question 5.
Write a program to find all the prime numbers up to a given number
Answer:

n = input("Enter the number”)


i = 2
flag = 0
while (i < n):
if (n%i)==0:
flag = 1
print n,“is composite”
break
i = i+ 1
if flag ==0 :
print n,“is prime”

Question 6.
Write a program to convert decimal number to binary.
Answer:

i=1
s=0
dec = int ( raw_input(“Enter the decimal to be converted:”))
while dec>0:
rem=dec%2
s=s + (i*rem)
dec=dec/2
i=i*10
print “The binary of the given number is:”,s raw_input()

Question 7.
Write a program to convert binary to decimal
Answer:
binary = raw_input(“Enter the binary string”)
decimal=0
for i in range(len(str(binary))):
power=len (str (binary)) - (i+1)
decimal+=int(str(binary)[i])*(2**power)
print decimal

Question 8.
Write a program to input two complex numbers and to find sum of the given complex numbers.
Answer:

areal = input("Enter real part of first complex number”)


aimg = input("Enter imaginary part of first complex number”)
breal = input("Enter real part of second complex number”)
bimg = input("Enter imaginary part of second complex number”)
totreal = areal + breal
totimg = aimg + bimg
print “Sum of the complex numbers=",totreal, “+i”, totimg

Question 9.
Write a program to input two complex numbers and to implement multiplication of the given complex numbers.
Answer:

a = input("Enter real part of first complex number”)


b = input("Enter imaginary part of first complex number”)
c = input("Enter real part of second complex number”)
d = input("Enter imaginary part of second complex number”)
real= a*c - b*d
img= a*d + b*c
print “Product of the complex numbers=",real, “+i”,img

Question 10.
Write a program to find the sum of all digits of the given number.
Answer:

n = inputfEnter the number”)


rev=0
while (n>0):
a=n%10
sum = sum + a
n=n/10
print “Sum of digits=”,sum

Question 11.
Write a program to find the reverse of a number.
Answer:

n = input("Enter the number”)


rev=0
while (n>0):
a=n%10
rev=(rev*10)+a
n=n/10
print “Reversed number=”,rev

Question 12.
Write a program to print the pyramid.
1
22
333
4444
55555
Answer:

for i in range(1,6):
for j in range(1,i+1):
print i,
print

Question 13.
Write a program to input username and password and to check whether the given username and password are
correct or not.
Answer:

import string
usemame= raw_input(“Enter username”)
password = raw_input(“Enter password”)
if cmp(username.strip(),“XXX”)== 0:
if cmp(password,”123”) == 0:
print “Login successful”
else:
print “Password Incorrect”
else:
print “Username Incorrect”

Question 14.
Write a generator function generatesq () that displays the squareroots of numbers from 100 to n
where n is passed as an argument.
Answer:

import math
def generatesq (n) :
for i in range (100, n) :
yield (math, sqrt (i))

Question 15.
Write a method in Python to find and display the prime number between 2 to n.
Pass n as argument to the method.
Answer:

def prime (N) :


for a in range (2, N):
for I in range (2, a):
if N%i ==0 :
break print a
OR
def prime (N):
for a in range (2, N):
for I in range (2, a) :
if a%1= = 0 :
break
else :
print a

Question 16.
Write a program to input username and password and to check whether the given username and password are
correct or not.
Answer:
import string
usemame= raw_input(“Enter username”)
password = raw_input(“Enter password”)
if cmp(usemame.strip(),“XXX”)== 0:
if cmp(password,”123”) == 0:
print “Login successful”
else:
print “Password Incorrect”
else:
print “Username Incorrect”

Question 17.
Which string method is used to implement the following: [CBSE Text Book]

1. To count the number of characters in the string.


2. To change the first character of the string in capital letter.
3. To check whether given character is letter or a number.
4. To change lowercase to uppercase letter.
5. Change one character into another character.

Answer:

1. len(str)
2. str.title() or str.capitalize()
3. str.isalpha and str.isdigit()
4. lower(str[i])
5. str.replace(char, newchar)

Question 18.
Write a program to input any string and to find the number of words in the string.
Answer:

str = “Honesty is the best policy”


words = str.split()
print len(words)

Question 19.
Write a program to input n numbers and to insert any number in a particular position.
Answer:

n=input(“Enter no. of values")


num=[]
for i in range (n):
number=input(“Enter the number") num.append(number)
newno = input(“Enter the number to be inserted”)
pos = input(“Enter position”) num.insert(newno,pos)
print num

Question 20.
Write a program to input n numbers and to search any number from the list.
Answer:

n=input(“Enter no. of values”)


num=[]
flag=0
for i in range (n):
number=input(“Enter the number”)
num. append(number)
search = input(“Enter number to be searched")
for i in range(n):
if num[i]==search:
print search,“found at position”,i
flag=1
if flag==0:
print search, “not found in list”

Question 21.
Write a program to search input any customer name and display customer phone number
if the customer name is exist in the list.
Answer:

def printlist(s):
i=0
for i in range(len(s)):
print i,s[i]
i = 0
phonenumbers = [‘9840012345’,‘9840011111’,’ 9845622222’,‘9850012345’,‘9884412345’]
flag=0
number = raw_input(“Enter the phone number to be searched")
number = number.strip()
try:
i = phonenumbers.index(number)
if i >= 0:
flag=1
except ValueError:
pass
if(flag <>0):
print “\nphone number found in Phonebook at index”, i
else:
print'\iphonenumbernotfoundin phonebook”
print “\nPHONEBOOK”
printlist(phonenumbers)

Question 22.
Write a program to input n numbers and to reverse the set of numbers without using functions.
Answer:

n=input(“Enter no. of values”)


num=[]
flag=0
for i in range (n):
number=input(“Enter the number”)
num. append(number)
j=n-1
for i in range(n):
if i<=n/2:
num[i],num[j] = num[j],num[i]
j=j-1
else:
break
print num

Question 23.
Find and write the output of the following Python code: [CBSE Complementry-2016]

class Client:
def init (self, ID = 1, NM=”Noname”) #
constructor
self.CID = ID
self. Name = NM
def Allocate (self, changelD, Title) :
self.CID = self.CID + Changeld
self.Name = Title + self. Name
def Display (self) :
print (self. CID). "#”, self. Name)
C1 = Client ()
C2 = Client (102)
C3 = Client (205, ‘’Fedrick”)
C1 . Display ()
C2 . Display ()
C3 . Display ()
C2 . Allocate (4, "Ms.”)
C3 .Allocate (2, "Mr.”)
C1. Allocate (1, "Mrs.”)
C1. Display ()
C2 . Display ()
C3 . Display ()

Answer:

CID Name
— Fedrick
102 Mr. Fedrick
205 Mrs. Fedrick
— Mr. & Mrs. Fedrick

Question 24.
What will be the output of the following Python code considering the following set of inputs?

MAYA
Your 5 Apples
Mine2
412
Also, explain the try and except used in the code.
Count = 0
while True :
try:
Number=int (raw input ("Input a Number :"))
break
Except valueError :
Count=Count + 2
# For later versions of python, raw_input
# Should be consider as input

mehtods:
– DenCal () # Method to calcualte Density as People/Area
– Add () # Method to allow user to enter values Dcode, DName, People, Area and Call DenCal () Mehtod
– View () # Method to display all the data members also display a message “”High Population”
if the Density is more than 8000.
Answer:
Output is below
2 Re Enter Number
10 Re Enter Number
5 Input = Number
3 Input = number
Try and except are used for handling exception in the Pythan code.

Question 25.
Write a method in Python and display the prime numbers between 2 to N. Pass as argument to the methods.
Answer:
def prime (N) :
for a in range (2, N)
Prime=1
for I in range (2, a):
if a%i= = 0 :
Prime = 0
if Prime = = 1:
print a
OR
def prime (N) :
for a in range (2, N):
for I in range (2, a) :
if a%i = = 0:
break
else :
print a
OR
Any other correct code performing the same

Long Answer Type Questions (6 marks)

Question 1.
Aastha wnats to create a program that accepts a string and display the characters in the reverse
in the same line using a Stack. She has created the following code, help her by completing the
definitions on the basis of requirements given below:[CBSE SQP 2016]

Class mystack :
def inin (self):
selfe. mystr= # Accept a string
self.mylist= # Convert mystr to a list
# Write code to display while removing element from the stack.
def display (self) :
:
:

Answer:

class mystack :
def _init_ (self) :
self.myster= rawjnput ("Enter the string”)
self.mylist = list (self.mystr)
def display (self) :
x = len (self. mylist)
if (x > 0) :
for i in range (x) :
print self.mylist.pop (),
else :
print "Stack is empty”
Output Questions Working with functions Class 12
1. def Fun1():
          print(‘Python, let\’s fun with functions’)
    Fun1()
 
Ans.:
Python, let’s fun with functions
Explanation: Fun1 is a user-defined function having 1 statement with \ to print ‘ in output. 
 
2.def add(i):
        if(i*3%2==0):
            i*=i
        else:
            i*=4
        return i
    a=add(10)
    print(a)
   b=add(5)
   print(b)
 
Ans.:
100
  20
Explanation: In the first function call statement 10 is passed as a value, so i*3%2=10*3%2=30%2=0, hence
prints square of 10 i.e. 100. In the second function call statement 5 is passed as a value, so
i*3%2=5*3%2=15%2=1, hence else block will be executed, and its i=i*4 t*4=20. 
 
3. import math
    def area(r):
        return math.pi*r*r
    a=int(area(10))
    print(a)
 
Ans.:314
Explanation: In function, call value is passed 10. Hence the calculation will be 3.14*100=314.
 
4.def fun1(x, y):
        x = x + y
        y = x – y
        x = x – y
        print(‘a =’,x)
        print(‘b =’,y)
    a = 5
    b = 3
    fun1(a,b)
 
Ans.: 
a=3
b=5
Explanation:
a=5
b=3
fun1(5,3)
x=5+3=8
y=8-3=5
x=8-5=3
a=3
b=5
 
4. def div5(n):
        if n%5==0:
            return n*5
        else:
            return n+5
    
   def output(m=5):
        for i in range(0,m):
            print(div5(i),’@’,end=” “)
        print(”)
    output(7)
    output()
    output(3)
Ans.:
0 @ 6 @ 7 @ 8 @ 9 @ 25 @ 11 @
0@6@7@8@9@
0@6@7@
Explanation: In first calling for output(7) loop executes 7 times. and returns 5 as 25 and the rest will be
incremented by 5 hence the first line is generated. 
In the second calling function no value is passed so it takes the default argument and the loop terminates when
the of i is 5. 
In the third calling, the function value is passed as 3 so there is no value which a multiple of 5. 
 
5.def sum(*n):
        total=0
        for i in n:
            total+=i
            print(‘Sum=’, total)
    sum()
    sum(5)
    sum(10,20,30)
 
6.def func(b):
        global x
        print(‘Global x=’, x)
        y = x + b
        x = 7
        z = x – b
        print(‘Local x = ‘,x)
        print(‘y = ‘,y)
        print(‘z = ‘,z)
    x=5
    func(10)
 
7. def func(x,y=100):
        temp = x + y
        x += temp
        if(y!=200):
            print(temp,x,x)
    a=20
    b=10
    func(b)
    print(a,b)
    func(a,b)
    print(a,b)
 
8. def get(x,y,z):
        x+=y
        y-=1
        z*=(x-y)
        print(x,’#’,y,’#’,z)
    def put(z,y,x):
        x*=y
        y+=1
        z*=(x+y)
        print(x,’$’,y,’$’,z)
    a=10
    b=20
    c=5
    put(a,c,b)
    get(b,c,a)
    put(a,b,c)
    get(a,c,b)
 

In the next section Working with functions Class 12 questions and answers, we are going through error-based
questions.

Error-based questions working with functions class 12 computer


science
1. def in(a,b)
        a=a + b
        print(a.b)
        a=*b
        print(a**b)
In(8,2)
 
2. void get(x=10,y):
  x=x+y
    print(x,n,y)
 
3. // Program to compute the result
    def res():
        eng = 56
        math = 40
        sci = 60
        if eng<=35 || math<=35 ||
            sci=35
            print(‘Not Qualified’)
            else:
                print(“Qualified”)
 
4. a=5, b=10
    def swap(x,y):
        x = a + b
        y = x – y
        x = x – y
    swap(a)
    swap(15,34)
    swap(b)
    swap(a,b)
 
5. def cal_dis(qty,rate=50,dis_rate): #discount rate = 5%
        bil_amt = (qty*rate)*dis_rate
        print(bil_amt)
    caldis(10)
    cal_dis(10,50,0.05)
 
6. def Sum(C) #Method to find sum
         S=0
         for I in range(1,C+1):
               S+=I
         RETURN S
   print (Sum[2]) #Function Call
   print(Sum[5])
 

1. What will be the output of the following code?


print (type(type(int)))

(a)

type "int'

(b)

< class 'type' >

(c)

 Error

(d)
 < class "int' >

2. What will be the output of the following code?


L = ['a','b','c','d']
print (" ".join(L))

(a)

Error

(b)

 a b c d

(c)

['a':b':c':d']

(d)

 None

3. What is called when a function is defined inside a class?

(a)

Module

(b)

Class

(c)

Another function

(d)

Method

4. Which of the following is the use of idf) function in python?

(a)

Id() returns the identity of the object

(b)
 Every object doesn't have a unique ID

(c)

All of the mentioned

(d)

None of the mentioned

5. Suppose list1 is [3, 4, 5, 20, 5, 25, 1, 3], what is list after list1.pop(1)?

(a)

[3,4, 5, 20, 5, 25, 1, 3]

(b)

[1, 3, 3, 4, 5, 5, 20, 25]

(c)

[3,5, 20, 5, 25, 1, 3]

(d)

 [1,3,4,5,20,5,25]

6. Find and write the output of the following Python code:


def fun(s):
k=len(s) .
m=""
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('schooI2@com')

(a)

7. What do you understand by local and global scope of variables? How can you access a global variable
inside the function, if function has a variable with same name.

2
(a)

8. 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) (iii) (iv)

BLUE  BLUE  PINK  BLUEBLUE 

PINK  BLUEPINK  PINKGREEN  PINKPINK 

GREEN  BLUEPINKGREEN  GREENRED  GREENGREEN 

RED  BLUEPINKGREENRED   REDRED 

9. 2
10. (a)

11. How can we import a module in Python?

(a)

12. What are the differences between parameters and arguments?

(a)

13. What are default arguments?

(a)

14. What are keyword arguments?

(a)

15. What are the advantages of keyword arguments?

2
(a)

16. Write a generator function generatesq ( ) that displays the square roots of numbers from 100 to n where n
is passed as an argument.

(a)

17. What are the advantages of dividing a program into modules.

(a)

18. Differentiate between Built-in functions and user defined functions.

(a)

19. Differentiate between Built-in functions and functions defined in modules.

(a)

20. Write a program that reads a number, then converts it into octal, hexadecimal, ASCII and Unicode string
using built in functions of Python.

(a)

21. Write the corresponding Python expression for the following mathematical expressions:
i) 2-ye2y +4y ii) Iex- x2 - xI

(a)

22. Write a Python program using functions to calculate area of a triangle after obtaining its three sides.

(a)

23. How are following two statements different?


import math
from math import *

2
(a)

24. What will be the output of the following code


sinppet and why?
# module calculate.py
''''''This module will be imported"""
defsum 0:
"""Prints sum of 10 and 5"''''
b=5
a=10
print ("sum=",a+b)
return
def diff():
"""prints difference of 20 and 5"""
a=30
b=5
print ("Difference=", a-b)
return
print ("This will print something")
greet= "Hello!"
#Fun.py import calculate print calculate.gra

(a)

25. What is an execution frame?

(a)

26. What is the difference between passing mutable type arguments and immutable type arguments to the
function?

(a)

27. What are Positional arguments?

(a)

28. Is indentation required in Python?

(a)

29. What is a default parameter? How is it specified?


2

(a)

30. From the function calls given below for a function defined as def fun(p,t,r=7, c=8): determine which is
valid and which one is invalid. Give reasons.
(i) fun(p=5, t=2)
(ii) fun(c=2, r=7)
(iii) fun (80,p=7,r=2)

(a)

31. What is name resolution rule? Explain it.

(a)

32. What will be the output of the following program.?


1 def increase (x): (b) a=l
2 a= a+x                     def ft):
3 return                      a=10
4                                print(a)
5 a=20
6 b=5
7 increase (b)
8 print(a)

(a)

33. Spot the errors and rewrite the corrected codes.


total=0;
def sum(arg1, arg2) :
total = arg1 + arg2
print("Total:", total)
return total
sum (10,20)
print("Total:" total)

(a)

34. What will following function print when called?


def addEm (x,y,z):
return x+y+z
print(x+y+z)

2
(a)

35. Predict the output of the following codes.


(a) num=l (Each part carries 2 marks)
def myfunct):
returnnum
print (num)
print (myfunc ())
print (num)

(a)

36. Write a function to calculate volume of a box with appropriate default values for its parameters. Your
function should have the following input parameters:
a) Length of box b) width of box c) height of box

(a)

37. Write a function that takes a number as argument and calculates cube for it. The function does not return
a value. If there is no value passed to the function in function call, the function should calculate cube of
2.

(a)

38. Write a function that receives two string arguments and checks whether they are same-length strings
(returns True in this case otherwise False)

(a)

39. Write a function namely nthRoot() that receives two parameter x and n and return nth root of x ie. x1/n
The default value of n is 2

(a)

40. Write a function that takes two numbers and returns the number that has minimum one's digit.

(a)

41. Write a void function that receives a 4 digit number and calculates the sum of squares of first two digits
of the number and last two digits of the number egoif 1233 is passed as argument then function should
calculate (12)2+(33)2
2

(a)

42. Write a function to swap two numbers.

(a)

43. What are the rules to define a' function in Python?

(a)

44. What does the len() function do?

(a)

45. How can you make a module 'helloworld' out of these two functions?
def hello():
print ('Hello,',)
def world():
print ('World!')

(a)

46. Define pow(x, y) function in Python.

(a)

47. What is a Python module? What is its significance?

(a)

48. "Python has certain functions that you can readily use without having to write any special code." What
type of functions are these ?

(a)

49. What is the utility of built-in function help () ?


2

(a)

50. What is the utility of Python standard library's math module and random module?

(a)

51. Explain Scope of Variables.

(a)

52. Find the error


def minus (total, decrement)
output = total - decrement
return output

(a)

53. What would be the output produced by the following code:


import math
import random
print (math. ceil (random.random( )))

(a)

54. Find the error(s) in the following code and correct them:
1. def describe intelligent life form ():
2. height = input ("Enter the height")
3. raw_input ("Is it correct?")
4. weight = input ("Enter the weight")
5. favourite-game = input ("Enter favorite game")
6. print ("your height", height, 'and weight', weight)
7. print ("and your favourite game is", favouritism, '.')

(a)

55. Write a function that:


(i) Asks the user to input a diameter of circle in inches.
(ii) Sets a variable called radius to one half of that number.
(iii)Calculate the area of circle.
(iv) Print the area of circle with appropriate unit.
(v) Return this same amount as the output of the function
2

(a)

56. What would be the output of the following ?


Explain.
def f1()}:
n = 44
def f2 ():
n= 77
print ("value of n", n ())
print ("value of n",n)

(a)

57. What do you mean by globals() and locals() functions

(a)

58. What are docstrings ?How are they useful?

(a)

59. Explain global vs. local variables.

(a)

60. Explain anonymous functions.

(a)

61. Identify the following function definitions as void or non-void function.


(i) def fun():
print("Hello!")
(ii) def fun():
print("Hello!")
return(1)
(iii) def fun():
print("Hello!")
retum(1)
(iv) def fun():
return(2)
print("Hello")
2

(a)

62. How are docstring different from comments?

(a)

63. Give the output of the following code:


def Hello(Sum):
fori in Sum:
print(i)
S=("Hii", "Hello", "Namaste")
Hello(S)

(a)

*****************************************
Functions Important Questions Answer Keys

1. (b)

< class 'type' >

2. (b)

 a b c d

3. (d)

Method

4. (a)

Id() returns the identity of the object

5. (c)

[3,5, 20, 5, 25, 1, 3]

6. SCHOOLbbbbCOM
7. A global variable is a variable that is accessible globally. A local variable is one that is only accessibleto
the current scope, such as temporary variables used in a single function definition. A variable declared
outside of the function or in global scope is known as global variable. This means, global variable can be
accessed inside or outside of the function where as local variable can be used only inside the function.
We can access by declaring variable as global A.
8. Option (i) and (iv) are possible
PICKER maxval = 3, minval = 0
 

9. 1. using import
  Syntax:
  import < modulename1 >[,,< modulename2>,....
Example:
import math, cmath
2. using from
Syntax:
from < module name > import < function1 >[, <  function2  >,...... < functionn > ]

Example:
from fib import fib, fib2

10.

S.NO  Parameters  Arguments 

1 Values provided in  function header Values provided  in function call

(eg) def rnain ()


radius = 5.0
2 (eg) def area (r) : --->r is the parameter area (radius)
--->radius is the argument
 

11.  Python allows function arguments to have default values; if the function is called without the argument,
the argument gets its default value.
12. If there is a function with many parameters and we want to specify only some of them in function call,
then value for such parameters can be provided by using their names instead of the positions. These an;
called keyword arguments.
(e.g.) def simpleinterest(p, n=2, r=0.6):
def simpleinterest(p, r=0.2, n=3):
13. It is easier to use since we need not to remember the order of the arguments.
We can specify the values for only those parameters which we want, and others will have default values.
14. import math.
def generatesq (n):
for i in range (100, n):
yield (math. sqrt (i))
15. 1. It reduces complexity of the program.
2. It creates well-defined boundaries within the program.
3. It increases the reusability of the module.
16. Built in functions are predefined functions that are already defined in Python and can be used anytime.
e.g. len(), typet), int(), etc. User defined functions are defined by the programmer.
17. Built-in functions are predefined functions that are already defined in Python and can be used anytime
e.g. len(), type(), int() etc. Functions defined in modules are predefined in modules and can be used only
when the corresponding moduleis imported
e.g. to use predefined function sqrt() the math module needs to be imported as import math.
18. # Number system converter
import math
num=int (inputf''Enter a number:")
printt''Number entered = ", num) ,
octnum = oct(num)
hexnum= hex(num)
uninum= unicode(num)
asciinum= str(nurn)
print ("Octal equivalent", octnum)
print ("Hexadecimal equivalent" , hexnum)
print ("Unicode of number:", uninum)
print ("ASCIIcode of number:", asciinum)
19. i) 2-y * (math.exp(2*y))+4*y
ii) math.fabs(exp(x)-x**2-x)
20. # Program to calculate area of a triangle
import math
def artriangle (a.b,c):
"""This will use Heron's formula."?"
s=(a+b+c)/2
area=math.sqrt (s"(s-a)"(s-b)*(s-c))
return area
Fside=float (raw_input ("Enter first side:"))
Sside=fl.oat(raw_input("Entersecondside:"))
Tside=float(raw_input("EnterThirdside:"))
print ("Area of the triangle with sides", Fside, Sside,Tside, "is:",artriangle (Fside,Sside, Tside)
21. import math:When we use import math statement, a new namespace is setup with the same name as that
of the module and all the code of the module is interpreted and executed here Now all the defined
functions and variables of the module are available to the program.
from math import:When we use from math import" statement no new namespace is created. All the
functions and variables of the imported module are added to the namespace of the program. Now if there
are two variables with same name, one in the program and other in the imported module then the variable
of imported module is hidden by the program variable.
22. output:
This will print something.
Hello!
This happens because when we import a module its main program is executed so first the statement print
("This will print something") is executed and then print calculate greet is executed.
23. In Python, a block is executed in an execution frame. It contains:
*internal information for debugging
*name of the function
*values passed to the function
*variables created within function
*information about the next instruction to be executed.
24. When immutable type objects are given as arguments then their value can not be altered by the function
(i.e. only value is passed to the function) but when mutable type objects are passed their reference is
passed and hence the values can be altered.
25.  Positional arguments or Required arguments are those which must be provided for all parameters. The
values of arguments are matched with parameters position wise.
26. Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions,
etc is specified within an indented block. It is usually done using four space characters. If your code is
not indented necessarily, it will not execute accurately and will throw errors as well. 
27. A parameter having default value in the function header is known as a default parameter. A parameter
can be specified as default only if all the parameters on its right are specified as default. To specify a
default parameters syntax is
def < function header > (argl, arg2---arg x = < value >):
arg x will now be a default parameter with default value as the value specified.
28. (i) Valid as the arguments are used as keywords and rest are default arguments
(ii) Invalid as required argument p is not specified.
(iii) Invalid as two values for' p' are specified. One is positional and other is named.
29. Whenever a name reference is encountered in a program, Python follows name resolution rule or
LEGBrule. For every variable Python
(i) Check within its Local environment (legb), and uses it if available. Otherwise it moves to Enclosing
environment.
(ii) Then checks the Enclosing environment (legb) and uses it.if available. Otherwise it moves to Global
environment.
(iii) Now it checks the Global environment (legb) and uses the variable if available otherwise it moves to
Built-in Environment.
(iv) At last it checks the Built-in environment (legb) and uses the variable otherwise it  reports the
following error:
name < variable = not defined.
30. (a) This code will produce an error as in line 2 there is no value of a available to be used in RHS of the
assignment statement.
(b)1.
31. total=0
def sum (argl, arg2):
total=argl +arg2
print("Total:", total)
return total
sum (10,20)
print("Total:", total)
32. It will print nothing as before reaching the print statement, the program control encounters the return
statement.
33. 1
None
1
(b) num=1
def myfunc():
num=10
returnnum
print (num)
print (myfunc())
print (num)
1
10
1
(c) num=1
def myfunc():
globalnum
num=10
returnnum
print (num)
print (myfunc())
print (num)
1
10
10
d) a=10
y=5
def myfunc():
y=a
a=2
print ry="y,"a=",a)
print ("a+y=", a+y)
return a+y
print ("y=", y,"a=",a)
print (myfunc())
print ("y=", y, "a=",a)
Ans. Local variable name 'a' not defined.
e) def multiply (num1, num2):
ans=num1 *num2
print(num1, "times", num2, =", ans)
return(ans)
output=multiply (5,5)
Ans. 5 times 5 = 25
f) def first (s,i):
return s * second (i)
def second (n):
return n+3
print (first('*',2))
Ans. ***** 2
g) def add (a,b):
return a+b
def mul (a,b=5):
return a*b
def square (x):
return mul (x,x)
print (add (4, square(mul(2))))
print (add (4,square(square(2))))
print (4, squaretsquare(2)))
104
20
416
h) def execute (x,y = 200):
temp = x+y
print (temp, x,y)
a,b =50,20
execute (b)
execute (a,b)
execute (b,a)
Ans. 220 20 200
70 50 20
70 20 50
i) def execute (x,y= 200,z= [23,]):
temp=x+y+z[o]
print (temp, x, y)
a,b =50,20
c=[10,]
execute (b)
execute (y=a,x=b)
execute (x=b, 2= [a,],y=a)
Ans. 243 20 200
93 20 50
120 20 50
34. def volBox(len=1, wid=1, hei=1):
volume =len *wid*hei
return(volume)
35. def calcCube(num = 2):
cube = num **3
print ("Cube of", num, "is", cube)
return
36. def checkstring (str1, str2):
if len (str1) = =len(str2):
return (True)
else:
return (False)
37. def nthRoot(x, n=2):
res=x**(l/n)
return res
38. def mindigit (numl, num2):
if (numl) < (num2)::
return num1
else:
return num2
39. def calcsquareDigits(num):
sum = ((num% 100)**2)+ (int((num/l00))**2)
print ("sum of squares of first two and last two digits is",sum)
return
40. a = 5
b=9
def swap(c,d):
return d,c
swap(a,b)
41. You can define functions to provide the required functionality. Here are simple rules to define a function
in Python:
(1) Function blocks begin with the keyword def followed by the function name and parentheses ().
(2) Any input parameters or arguments should be placed within these  parentheses. You can also define
parameters inside these parentheses.
(3) The first statement of a function can be an optional statement, the documentation string of the
function or docstring.
(4) The code block within every function starts with a colon (:) and is indented.
(5) 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.
42. It gets the length of the string that you pass to it then returns it as a number.
43. hello ()
world ()
44. Return x raised to the power y. In particular, pow(1.0, x) and pow(x, 0.0)always return 1.0,even when x
is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is
undefined, and raises ValueError.
45. A 'module' is a chunk of python code that exists in its own (.py) file and is intended to be used by python
code outside itself. Modules allow one to bundle together code in a form in which it can easily be used
later.
The modules can be 'imported' in other programs so the function and other definitions in imported
modules becomes available to code that imports them.
46. The predefined functions that are always available for use are known as python's built-in functions.
For example:
len(), type (), int (), raw_input () etc.
47. Python's built in function help ( ) is very useful. When it is provided with a program-name or a module-
name or a function-name as an argument, it displays the documentation of the argument as help. It also
displays the docstrings within its passed-argument's definition.
For example:
help (math)
will display the documentation related to module math.
48. math module is used for mathematics related functions and random module implements pseudo-random
number generators for various distributions.
49. All variables in a program may not be accessible at all locations in that program. This depends on where
you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particularidentifier.
There are two basic scopes of variables in Python:
(1) Global variables
(2) Local variables
50. The function's header has colon missing at the end.
So add colon (:) at end of header line.
Thus, the correct code is
def minus (total, decrement) :
output = total- decrement
return output
51. The output would be: 1.0
random.random( ) would generate a number in the range (0.0, 1.0) but math.ceil ( ) will return ceiling
number for this range, which is 1.0 for all the numbers in this range.
Thus the output produced will always be 1.0.
52. Here, function name contains spaces. But function name should be a valid Python identifier with no
spaces in between. And here, no variable is defined to obtain value being input. Lines 4 and 6 are badly
indented; being part of same function, those should be at the same indentation level as that of lines 2, 3, 5
and 7. And also, variable favourite-game is an invalid identifier as it contains a hyphen, but it should
have been an underscore.
53. def area_circle ():
import math
diameter= float (raw_input ("Enter the diameter in Inches))
radius = diameter/2
area_circle_inches = (math.pi) * (radius * * 2)
print ("The area of circle",area_circle_ inches,"sq inch")
return (area_circle_inches)
54. The output will show an error at line 5 as: NameError: name In'is not defined
55. The globals( ) and locals( ) functions can be used to return the names in the global and local namespaces
depending on the location from where they are called. If Iocals() is called from within a function, it will
return all the names that can be accessed locally from that function. If globals() is called from within a
function, it will return all the names that can be accessed globally from that function. The return type of
both these functions is dictionary. Therefore, names can be extracted using the keys() function.
56. A docstring is just a regular python triple- quoted string that is the first thing in a function body or a
module or a class. When executing a function body the docstring does not do anything like comments,
but Python stores it as part of the function documentation. This documentation can later be displayed
using helpt) function. So even though docstrings appear like comments but these are different from
comments.
57. Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.
This means that local variables can be accessed only inside the function in which they are declared
whereas global variables can be accessed throughout the. program body by all functions. When you call a
function, the variables declared inside it are brought into scope.
58. You can use the lambda keyword to create small anonymous functions. These functions are called
anonymous because they are not declared in the standard manner by using the def keyword, lambda
functions haye their own local namespace and cannot access variables other than those in their parameter
list and those in the global namespace.
59. (i) and (ii) are void function
(iii) and (iv) are non-void functions
60. Docstrings are different from comments because docstrings are stored as documentation of the
corresponding module or function or class and can be displayed using helpt) function with name of the
corresponding module/ function/class as parameter e.g. help (math), help(math.pow) etc. This is not true
with comments.
61. Output
Hii
Hello
Namaste 

You might also like