[go: up one dir, main page]

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

Chapter 8

The document contains solutions to various Python programming questions related to data types, operators, functions and modules. Multiple choice and code-based questions covering core Python concepts like truth values, strings, integers, floats, variables, expressions and errors are included.

Uploaded by

subhITsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
174 views30 pages

Chapter 8

The document contains solutions to various Python programming questions related to data types, operators, functions and modules. Multiple choice and code-based questions covering core Python concepts like truth values, strings, integers, floats, variables, expressions and errors are included.

Uploaded by

subhITsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter 8

Question 1

What is the result produced by (i) bool (0) (ii) bool (str(0))? Justify the outcome.

Answer

(i) bool (0)

The result is False as truth value of 0 is falsetval

(ii) bool (str(0))

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.

6 == input ("Value 1:")


6 == int(input ("value 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

What will following code print?

a = va = 3
b = va = 3
print (a, b)
Answer

This Python code prints:


3 3

Question 4b

What will following code print?

a = 3
b = 3.0
print (a == b)
print (a is b)
Answer

This Python code prints:

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

What will be the output of following Python code?

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

What will be the output of following Python code?

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

Consider the following expression:

x = "and" * (3 + 2) > "or" + "4"

What is the data type of value that is computed by this expression?

Answer

The data type of value that is computed by this expression is bool.

    x = "and" * (3 + 2) > "or" + "4"


⇒ x = "and" * 5 > "or" + "4"
⇒ x = "andandandandand" > "or4"
⇒ x = False

Question 9

Consider the following code segment:

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

The error is:

TypeError: can only concatenate str (not "int") to str

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.

To correct it, we need to cast a to int like this:

a = int(input())

Question 10

Consider the following code segment:


a = input("Enter the value of a:")
b = input("Enter the value of b:")
print(a + b)
If the user runs the program and enters 11 for a and 9 for b then what will the above code display?

Answer

Output

Enter the value of a:11


Enter the value of b:9
119

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".

The corrected code is:

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.

a = float(input("Enter the length of the first side:"))


b = float(input("Enter the length of the second side:"))
h = sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)
When this program is run, the following output is generated (note that input entered by the user is shown in
bold):

Enter the length of the first side: 3


Enter the length of the second side: 4
Traceback (most recent call last):
h = sqrt(a * a + b * b)
NameError: name 'sqrt' is not defined
Why is this error occurring? How would you resolve it ?

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.

a = float(input("Enter the length of the first side:"))


b = float(input("Enter the length of the second side:"))
h = sqrt(a * a + b * b)
print("The length of the hypotenuse is", h)
After adding import math to the code given above, what other change(s) are required in the code to make it
fully work ?

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

(b) "3" + "Hello"

(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

What is the output produced by following code?

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

print(int(s[0]) + int(s[1]) + int(s[2]) + int(s[3]) + int(s[4]))

Question 17

Predict the output if e is given input as 'True':

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

1. As 0 < 5 is True so b value of b becomes True and its type is bool.


2. print (a == b) gives True as a and b both are True.
3. print (a is b) gives True as a and b both being True point to the same object in memory.
4. Similarly print (c == d) and print (c is d) give True as c and d both are string and point to the
same object in memory.
5. The user input for e is True so e is of type string having value "True".
6. As value of strings c and e is "True" so print (c == e) gives True.
7. Even though the values of strings c and e are same, they point to different objects in memory
so print (c is e) gives False.

Question 18a

Find the errors(s)

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

Find the errors(s)

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

Find the errors(s)

print (type (int("123")))


print (type (int("Hello")))
print (type (str("123.0")))
Answer
In the line print (type (int("Hello"))), string "Hello" is given as an argument to int() but it cannot be
converted into a valid integer so it causes an error.

Question 18d

Find the errors(s)

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

Find the errors(s)

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

Find the errors(s)

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

What will be the output produced?

x, y, z = True, False, False


a = x or (y and z)
b = (x or y) and z
print(a, b)
Answer

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

What will be the output produced?

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

What will be the output produced?

s = 'Sipo'
s1 = s + '2'
s2 = s * 2
print(s1)
print(s2)
Answer

Output

Sipo2
SipoSipo

Explanation

1. s1 = s + '2' concatenates 'Sipo' and '2' storing 'Sipo2' in s1.


2. s2 = s * 2 repeats 'Sipo' twice storing 'SipoSipo' in s2.

Question 19d

What will be the output produced?

w, x, y, z = True , 4, -6, 2
result = -(x + z) < y or x ** z < 10
print(result)
Answer

Output
False

Explanation

    -(x + z) < y or x ** z < 10


⇒ -(4 + 2) < -6 or 4 ** 2 < 10
⇒ -6 < -6 or 4 ** 2 < 10
⇒ -6 < -6 or 16 < 10
⇒ False or False
⇒ False

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.

probability = input("Type a number between 0 and 1: ")


print("Out of 150 tries, the odds are that only", (probability * 150), "will
succeed.")
[Hint. Consider its datatype.]

Answer

The corrected program is below:

probability = float(input("Type a number between 0 and 1: "))


print("Out of 150 tries, the odds are that only", (probability * 150), "will
succeed.")

Question 21

Consider the code given below:

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 ?

(a) 655, 705, 220


(b) 380, 382, 505
(c) 100, 500, 999
(d) 345, 650, 110

Answer

The possible outcomes of the above code can be:

Option (a) — 655, 705, 220


Option (d) — 345, 650, 110
Maximum number can be 995 and minimum number can be 100.

Question 22

Consider the code given below:

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

The possible outcomes of the above code can be:

Option (a) — 12 45 22

Maximum number can be 90 and minimum number can be 0.

Question 23

Consider the code given below:

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 ?

(a) 0.5 1.6 9.8


(b) 10.0 1.0 0.0
(c) 0.0 5.6 8.7
(d) 0.0 7.9 10.0

Answer

The possible outcomes of the above code can be:

Option (a) — 0.5 1.6 9.8


Option (c) — 0.0 5.6 8.7
Maximum number can be 9.999999..... and minimum number can be 0.

Question 24

Consider the code given below:

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

The correct output of the above code is:

Option (c) — 8 7 7.5

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

Under what conditions will this code fragment print "water"?


if temp < 32 :
print ("ice")
elif temp < 212:
print ("water")
else :
print ("steam")
Answer

When value of temp is greater than or equal to 32 and less than 212 then this code fragment will print
"water".

Question 3

What is the output produced by the following code?

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

What is the error in following code? Correct the code:

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

What is the output of the following lines of code?

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

The corrected code is below:

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

What is following code doing? What would it print for input as 3?


n = int(input( "Enter an integer:" ))
if n < 1 :
print ("invalid value")
else :
for i in range(1, n + 1):
print (i * i)
Answer

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")
(b)

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

Rewrite the following code fragment using for loop:

i = 100
while (i > 0) :
print (i)
i -= 3
Answer

for i in range(100, 0, -3) :


print (i)

Question 9b

Rewrite the following code fragment using for loop:

while num > 0 :


print (num % 10)
num = num/10
Answer

l = [1]
for x in l:
l.append(x + 1)
if num <= 0:
break
print (num % 10)
num = num/10

Question 9c

Rewrite the following code fragment using for loop:

while num > 0 :


count += 1
sum += num
num –= 2
if count == 10 :
print (sum/float(count))
break
Answer

for i in range(num, 0, -2):


count += 1
sum += i
if count == 10 :
print (sum/float(count))
break

Question 10a

Rewrite following code fragment using while loops :

min = 0
max = num
if num < 0 :
min = num
max = 0 # compute sum of integers
# from min to max

for i in range(min, max + 1):


sum += i
Answer

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

Rewrite following code fragment using while loops :

for i in range(1, 16) :


if i % 3 == 0 :
print (i)
Answer

i = 1
while i < 16:
if i % 3 == 0 :
print (i)
i += 1

Question 10c

Rewrite following code fragment using while loops :

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

Predict the output of the following code fragments:

count = 0
while count < 10:
print ("Hello")
count += 1
Answer

Output

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

Explanation

The while loop executes 10 times so "Hello" is printed 10 times

Question 11b

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

x = 45
while x < 50 :
print (x)
Answer

This is an endless (infinite) loop that will keep printing 45 continuously.

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

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

for q in range(100, 50, -10):


print (q)
Answer

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

Predict the output of the following code fragments:

for z in range(-500, 500, 100):


print (z)
Answer

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

Predict the output of the following code fragments:

for y in range(500, 100, 100):


print (" * ", y)
Answer

This code generates No Output.

The for loop doesn't execute as range(500, 100, 100) returns an empty sequence — [ ].

Question 11k

Predict the output of the following code fragments:

x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer

This code generates No Output.

Explanation

The x-y * 2 in range(x-y * 2) is evaluated as below:


    x - y * 2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒0

Thus range(x-y * 2) is equivalent to range(0) which returns an empty sequence — [ ].

Question 11l

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

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

Predict the output of the following code fragments:

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

What is the output of the following code?

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

Python program given in Option (b) implements this flowchart:

while True :
n = int(input("Enter an int:"))
if n == A1 :
continue
elif n == A2 :
break
else :
print ("what")
print ("ever")

Question 15

Find the error. Consider the following program :

a = int(input("Enter a value: "))


while a != 0:
count = count + 1
a = int(input("Enter a value: "))
print("You entered", count, "values.")
It is supposed to count the number of values entered by the user until the user enters 0 and then display the
count (not including the 0). However, when the program is run, it crashes with the following error message
after the first input value is read :

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.")

You might also like