Chapter 8
Chapter 8
Question 1
What is the result produced by (i) bool (0) (ii) bool (str(0))? Justify the outcome.
Answer
The result is True as str(0) converts 0 to string "0". As it becomes a non-empty string so its truth value is
truetval
Question 2
What will be the output, if input for both the statements is 5 + 4/2.
Answer
Output of first statement is False as '5 + 4/2' is entered as a string so it cannot be equal to the number 6.
The second statement gives an error as int() function cannot convert the string '5 + 4/2' to a valid integer.
Question 3
Following Python code has an expression with all integer values. Why is the result in floating point form?
a, b, c = 2, 3, 6
d = a + b * c/b
print(d)
Answer
The output of the above Python code is 8.0. Division operator is present in the expression. The result of
Division operator is of float type. Due to implicit conversion, other operand in this expression are also
converted to float type and hence the final result is in floating point form.
Question 4a
a = va = 3
b = va = 3
print (a, b)
Answer
Question 4b
a = 3
b = 3.0
print (a == b)
print (a is b)
Answer
True
False
As values of a and b are equal so equality operator returns True. a is of int type and b is of float type so a
and b are different objects so a is b returns False.
Question 5a
What will be output produced by following code? State reason for this output.
a, b, c = 1, 1, 2
d = a + b
e = 1.0
f = 1.0
g = 2.0
h = e + f
print(c == d)
print(c is d)
print(g == h)
print(g is h)
Answer
Output
True
True
True
False
Explanation
Value of d becomes 2 and as values of c and d are equal so print(c == d) prints True.
Question 5b
What will be output produced by following code? State reason for this output.
a = 5 - 4 - 3
b = 3**2**3
print(a)
print(b)
Answer
Output
-2
6561
Explanation
a = 5 - 4 - 3
⇒a=1-3
⇒ a = -2
The exponentiation operator (**) has associativity from right to left so:
b = 3**2**3
⇒ b = 3**8
⇒ b = 6561
Question 5c
What will be output produced by following code? State reason for this output.
a, b, c = 1, 1, 1
d = 0.3
e=a+b+c-d
f=a+b+c == d
print(e)
print(f)
Answer
Output
2.7
False
Explanation
e = a+b+c-d
⇒ e = 1+1+1-0.3
⇒ e = 3-0.3
⇒ e = 2.7
As 0.3 is float so implicit conversion converts 3 also to float and result of the expression is of float type.
f = a + b + c == d
⇒ f = 1 + 1 + 1 == 0.3
⇒ f = 3 == 0.3
⇒ f = False
Question 6a
a = 12
b = 7.4
c = 1
a -= b
print(a, b)
a *= 2 + c
print(a)
b += a * c
print(b)
Answer
Output
4.6 7.4
13.799999999999999
21.2
Explanation
a -= b
⇒a=a-b
⇒ a = 12 - 7.4
⇒ a = 4.6
a *= 2 + c
⇒ a = 4.6 * (2 + c)
⇒ a = 4.6 * (2 + 1)
⇒ a = 4.6 * 3
⇒ a = 13.799999999999999
b += a * c
⇒ b = b + (a * c)
⇒ b = 7.4 + (13.799999999999999 * 1)
⇒ b = 7.4 + 13.799999999999999
⇒ b = 21.2
Question 6b
x, y = 4, 8
z = x/y*y
print(z)
Answer
Output
4.0
Explanation
z = x/y*y
⇒ z = 4/8*8
⇒ z = 0.5*8
⇒ z = 4.0
Question 7
Make change in the expression for z of previous question so that the output produced is zero. You cannot
change the operators and order of variables. (Hint. Use a function around a sub-expression)
Answer
x, y = 4, 8
z = int(x/y)*y
print(z)
Question 8
Answer
Question 9
a = input()
b = int(input())
c = a + b
print(c)
When the program is run, the user first enters 10 and then 5, it gives an error. Find the error, its reason and
correct it
Answer
It occurs because a is of type string but b is of type int. We are trying to add together a string operand and an
int operand using addition operator. This is not allowed in Python hence this error occurs.
a = int(input())
Question 10
Answer
Output
Explanation
input() function accepts user input as string type. The data type of a and b is string not int so addition
operator concatenates them to print 119 instead of 20.
Question 11
Find out the error and the reason for the error in the following code. Also, give the corrected code.
a, b = "5.0", "10.0"
x = float(a/b)
print(x)
Answer
a and b are defined as strings not float or int. Division operator doesn't support strings as its operand so we
get the error — unsupported operand type(s) for /: "str" and "str".
a, b = 5.0, 10.0
x = float(a/b)
print(x)
Question 12
Consider the following program. It is supposed to compute the hypotenuse of a right triangle after the user
enters the lengths of the other two sides.
Answer
The error is coming because math module is not imported in the code. To resolve it, we should import the
math module using the import statement import math.
Question 13
Consider the following program. It is supposed to compute the hypotenuse of a right triangle after the user
enters the lengths of the other two sides.
Answer
After adding import math statement, we need to change the line h = sqrt(a * a + b * b) to h =
math.sqrt(a * a + b * b). The corrected working code is below:
import math
a = float(input("Enter the length of the first side:"))
b = float(input("Enter the length of the second side:"))
h = math.sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)
Question 14
Which of the following expressions will result in an error message being displayed when a program
containing it is run?
(a) 2.0/4
(c) 4 % 15
(d) int("5")/float("3")
(e) float("6"/"2")
Answer
(a) No Error
(b) No Error
(c) No Error
(d) No Error
(e) This will cause an error of unsupported operand types as using division operator on string types is not
allowed in Python.
Question 15a
Following expression does not report an error even if it has a sub-expression with 'divide by zero' problem:
3 or 10/0
What changes can you make to above expression so that Python reports this error?
Answer
Interchanging the operands of or operator as shown below will make Python report this error:
10/0 or 3
Question 15b
a, b = bool(0), bool(0.0)
c, d = str(0), str(0.0)
print (len(a), len(b))
print (len(c), len(d))
Answer
The above code will give an error as the line print (len(a), len(b)) is calling len function with bool
arguments which is not allowed in Python.
Question 16
Given a string s = "12345". Can you write an expression that gives sum of all the digits shown inside the
string s i.e., the program should be able to produce the result as 15 (1+2+3+4+5).
[Hint. Use indexes and convert to integer]
Answer
Question 17
a = True
b = 0 < 5
print (a == b)
print (a is b)
c = str (a)
d = str (b)
print (c == d)
print (c is d)
e = input ("Enter :")
print (c == e)
print (c is e)
Answer
Output
True
True
True
True
Enter :True
True
False
Explanation
Question 18a
name = "HariT"
print (name)
name[2] = 'R'
print (name)
Answer
The line name[2] = 'R' is trying to assign the letter 'R' to the second index of string name but strings are
immutable in Python and hence such item assignment for strings is not supported in Python.
Question 18b
a = bool (0)
b = bool (1)
print (a == false)
print (b == true)
Answer
false and true are invalid literals in Python. The correct boolean literals are False and True.
Question 18c
Question 18d
pi = 3.14
print (type (pi))
print (type ("3.14"))
print (type (float ("3.14")))
print (type (float("three point fourteen")))
Answer
In the line print (type (float("three point fourteen"))) , string "three point fourteen" is given as an
argument to float() but it cannot be converted into a valid floating-point number so it causes an error.
Question 18e
print ("Hello" + 2)
print ("Hello" + "2")
print ("Hello" * 2)
Answer
The line print ("Hello" + 2) causes an error as addition operator (+) cannot concatenate a string and an
int.
Question 18f
print ("Hello"/2)
print ("Hello" / 2)
Answer
Both the lines of this Python code will give an error as strings cannot be used with division operator (/).
Question 19a
Output
True False
Explanation
1. x or (y and z)
⇒ True or (False and False)
⇒ True
2. (x or y) and z
⇒ (True or False) and False
⇒ True and False
⇒ False
Question 19b
x, y = '5', 2
z = x + y
print(z)
Answer
This code produces an error in the line z = x + y as operands of addition operator (+) are string and int,
respectively which is not supported by Python.
Question 19c
s = 'Sipo'
s1 = s + '2'
s2 = s * 2
print(s1)
print(s2)
Answer
Output
Sipo2
SipoSipo
Explanation
Question 19d
w, x, y, z = True , 4, -6, 2
result = -(x + z) < y or x ** z < 10
print(result)
Answer
Output
False
Explanation
Question 20
Program is giving a weird result of "0.50.50.50.50.50.50..........". Correct it so that it produces the correct
result which is the probability value (input as 0.5) times 150.
Answer
Question 21
import random
r = random.randrange(100, 999, 5)
print(r, end = ' ')
r = random.randrange(100, 999, 5)
print(r, end = ' ')
r = random.randrange(100, 999, 5)
print(r)
Which of the following are the possible outcomes of the above code ? Also, what can be the maximum and
minimum number generated by line 2 ?
Answer
Question 22
import random
r = random.randint(10, 100) - 10
print(r, end = ' ')
r = random.randint(10, 100) - 10
print(r, end = ' ')
r = random.randint(10, 100) - 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum and
minimum number generated by line 2?
(a) 12 45 22
(b) 100 80 84
(c) 101 12 43
(d) 100 12 10
Answer
Option (a) — 12 45 22
Question 23
import random
r = random.random() * 10
print(r, end = ' ')
r = random. random() * 10
print(r, end = ' ')
r = random.random() * 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum and
minimum number generated by line 2 ?
Answer
Question 24
import statistics as st
v = [7, 8, 8, 11, 7, 7]
m1 = st.mean(v)
m2 = st.mode(v)
m3 = st.median(v)
print(m1, m2, m3)
Which of the following is the correct output of the above code?
(a) 7 8 7.5
(b) 8 7 7
(c) 8 7 7.5
(c) 8.5 7 7.5
Answer
Chapter 9
Question 1
Rewrite the following code fragment that saves on the number of comparisons:
if (a == 0) :
print ("Zero")
if (a == 1) :
print ("One")
if (a == 2) :
print ("Two")
if (a == 3) :
print ("Three")
Answer
if (a == 0) :
print ("Zero")
elif (a == 1) :
print ("One")
elif (a == 2) :
print ("Two")
elif (a == 3) :
print ("Three")
Question 2
When value of temp is greater than or equal to 32 and less than 212 then this code fragment will print
"water".
Question 3
x = 1
if x > 3 :
if x > 4 :
print ("A", end = ' ')
else :
print ("B", end = ' ')
elif x < 2:
if (x != 0):
print ("C", end = ' ')
print ("D")
Answer
Output
C D
Explanation
As value of x is 1 so statements in the else part of outer if i.e. elif x < 2: will get executed. The
condition if (x != 0) is true so C is printed. After that the statement print ("D") prints D.
Question 4
weather = 'raining'
if weather = 'sunny' :
print ("wear sunblock")
elif weather = "snow":
print ("going skiing")
else :
print (weather)
Answer
In this code, assignment operator (=) is used in place of equality operator (==) for comparison. The
corrected code is below:
weather = 'raining'
if weather == 'sunny' :
print ("wear sunblock")
elif weather == "snow":
print ("going skiing")
else :
print (weather)
Question 5
if int('zero') == 0 :
print ("zero")
elif str(0) == 'zero' :
print (0)
elif str(0) == '0' :
print (str(0))
else:
print ("none of the above")
Answer
The above lines of code will cause an error as in the line if int('zero') == 0 :, 'zero' is given to int()
function but string 'zero' doesn't have a valid numeric representation.
Question 6
Find the errors in the code given below and correct the code:
if n == 0
print ("zero")
elif : n == 1
print ("one")
elif
n == 2:
print ("two")
else n == 3:
print ("three")
Answer
if n == 0 : #1st Error
print ("zero")
elif n == 1 : #2nd Error
print ("one")
elif n == 2: #3rd Error
print ("two")
elif n == 3: #4th Error
print ("three")
Question 7
The code will print the square of each number from 1 till the number given as input by the user if the input
value is greater than 0. Output of the code for input as 3 is shown below:
Enter an integer:3
1
4
9
Question 8
How are following two code fragments different from one another? Also, predict the output of the following
code fragments :
(a)
n = int(input("Enter an integer:"))
if n > 0 :
for a in range(1, n + n) :
print (a / (n/2))
else :
print ("Now quiting")
Answer
In part (a) code, the else clause is part of the loop i.e. it is a loop else clause that will be executed when the
loop terminates normally. In part (b) code, the else clause is part of the if statement i.e. it is an if-else clause.
It won't be executed if the user gives a greater than 0 input for n.
Output of part a:
Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335
Now quiting
Output of part b:
Enter an integer:3
0.6666666666666666
1.3333333333333333
2.0
2.6666666666666665
3.3333333333333335
Question 9a
i = 100
while (i > 0) :
print (i)
i -= 3
Answer
Question 9b
l = [1]
for x in l:
l.append(x + 1)
if num <= 0:
break
print (num % 10)
num = num/10
Question 9c
Question 10a
min = 0
max = num
if num < 0 :
min = num
max = 0 # compute sum of integers
# from min to max
min = 0
max = num
if num < 0 :
min = num
max = 0 # compute sum of integers
# from min to max
i = min
while i <= max:
sum += i
i += 1
Question 10b
i = 1
while i < 16:
if i % 3 == 0 :
print (i)
i += 1
Question 10c
for i in range(4) :
for j in range(5):
if i + 1 == j or j + 1 == 4 :
print ("+", end = ' ')
else :
print ("o", end = ' ')
print()
Answer
i = 0
while i < 4:
j = 0
while j < 5:
if i + 1 == j or j + 1 == 4 :
print ("+", end = ' ')
j += 1
else :
print ("o", end = ' ')
i += 1
print()
Question 11a
count = 0
while count < 10:
print ("Hello")
count += 1
Answer
Output
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Explanation
Question 11b
x = 10
y = 0
while x > y:
print (x, y)
x = x - 1
y = y + 1
Answer
Output
10 0
9 1
8 2
7 3
6 4
Explanation
x y Output Remarks
10 0 10 0 1st Iteration
10 0
9 1 2nd Iteration
91
10 0
8 2 91 3rd Iteration
82
10 0
91
7 3 4th Iteration
82
73
10 0
91
6 4 82 5th Iteration
73
64
Question 11c
keepgoing = True
x=100
while keepgoing :
print (x)
x = x - 10
if x < 50 :
keepgoing = False
Answer
Output
100
90
80
70
60
50
Explanation
Inside while loop, the line x = x - 10 is decreasing x by 10 so after 5 iterations of while loop x will
become 40. When x becomes 40, the condition if x < 50 becomes true so keepgoing is set
to False due to which the while loop stops iterating.
Question 11d
x = 45
while x < 50 :
print (x)
Answer
As the loop control variable x is not updated inside the loop neither there is any break statement inside the
loop so it becomes an infinite loop.
Question 11e
for x in [1,2,3,4,5]:
print (x)
Answer
Output
1
2
3
4
5
Explanation
x will be assigned each of the values from the list one by one and that will get printed.
Question 11f
for x in range(5):
print (x)
Answer
Output
0
1
2
3
4
Explanation
range(5) will generate a sequence like this [0, 1, 2, 3, 4]. x will be assigned each of the values from this
sequence one by one and that will get printed.
Question 11g
for p in range(1,10):
print (p)
Answer
Output
1
2
3
4
5
6
7
8
9
Explanation
range(1,10) will generate a sequence like this [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]. p will be assigned each of the
values from this sequence one by one and that will get printed.
Question 11h
Output
100
90
80
70
60
Explanation
range(100, 50, -10) will generate a sequence like this [100, 90, 80, 70, 60]. q will be assigned each of the
values from this sequence one by one and that will get printed.
Question 11i
Output
-500
-400
-300
-200
-100
0
100
200
300
400
Explanation
range(-500, 500, 100) generates a sequence of numbers from -500 to 400 with each subsequent
number incrementing by 100. Each number of this sequence is assigned to z one by one and then z gets
printed inside the for loop.
Question 11j
The for loop doesn't execute as range(500, 100, 100) returns an empty sequence — [ ].
Question 11k
x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer
Explanation
Question 11l
for x in [1,2,3]:
for y in [4, 5, 6]:
print (x, y)
Answer
Output
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Explanation
For each iteration of outer loop, the inner loop will execute three times generating this output.
Question 11m
for x in range(3):
for y in range(4):
print (x, y, x + y)
Answer
Output
0 0 0
0 1 1
0 2 2
0 3 3
1 0 1
1 1 2
1 2 3
1 3 4
2 0 2
2 1 3
2 2 4
2 3 5
Explanation
For each iteration of outer loop, the inner loop executes four times (with value of y ranging from 0 to 3)
generating this output.
Question 11n
c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)
Answer
Output
50
Explanation
Outer loop executes 10 times. For each iteration of outer loop, inner loop executes 5 times. Thus, the
statement c += 1 is executed 10 * 5 = 50 times. c is incremented by 1 in each execution so final value of c
becomes 50.
Question 12
for i in range(4):
for j in range(5):
if i + 1 == j or j + 1 == 4:
print ("+", end = ' ')
else:
print ("o", end = ' ')
print()
Answer
Output
o + o + o o o + + o o o o + o o o o + +
Explanation
Outer loop executes 4 times. For each iteration of outer loop, inner loop executes 5 times. Therefore, the
total number of times body of inner loop gets executed is 4 * 5 = 20. Thats why there are 20 characters in the
output (leaving spaces). When the condition is true then + is printed else o is printed.
Question 13
In the nested for loop code below, how many times is the condition of the if clause evaluated?
for i in range(4):
for j in range(5):
if i + 1 == j or j + 1 == 4:
print ("+", end = ")
else:
print ("o", end = ")
print()
Answer
Outer loop executes 4 times. For each iteration of outer loop, inner loop executes 5 times. Therefore, the
total number of times the condition of the if clause gets evaluated is 4 * 5 = 20.
Question 14
Which of the following Python programs implement the control flow graph shown?
(a)
while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
else:
print ("ever")
(b)
while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
print ("ever")
(c)
while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
print ("what")
print ("ever")
Answer
while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
print ("ever")
Question 15
Enter a value: 14
Traceback (most recent call last):
File "count.py", line 4, in <module>
count = count + 1
NameError: name 'count' is not defined
What change should be made to this program so that it will run correctly ? Write the modification that is
needed into the program above, crossing out any code that should be removed and clearly indicating where
any new code should be inserted.
Answer
The line count = count + 1 is incrementing the value of variable count by 1 but the
variable count has not been initialized before this statement. This causes an error when trying to execute
the program. The corrected program is below:
count = 0 #count should be initialized before incrementing
a = int(input("Enter a value: "))
while a != 0:
count = count + 1
a = int(input("Enter a value: "))
print("You entered", count, "values.")