Flow of Control
Flow of Control
Question 1
Answer
1. A header line which begins with a keyword and ends with a colon.
2. A body containing a sequence of statements at the same level of indentation.
Question 2
Answer
Question 3
Answer
pass
When pass statement is encountered, Python does nothing and moves to next statement in the
flow of control.
It is needed in those instances where the syntax of the language requires the presence of a
statement but where the logic of the program does not.
Question 4
pass
Question 5
What is an algorithm?
Answer
An algorithm is defined as the sequence of instructions written in simple English that are
required to get the desired results. It helps to develop the fundamental logic of a problem that
leads to a solution.
Question 6
Answer
Question 7
Answer
Question 8
Answer
An entry-controlled loop checks the condition at the time of entry. Only if the condition is
true, the program control enters the body of the loop.
Question 9
Answer
Question 10
What is the difference between else clause of if-else and else clause of Python loops?
Answer
The else clause of an if-else statement is executed when the condition of the if statement
results into false. The else clause of a loop is executed when the loop is terminating normally
i.e., when its test condition has become false for a while loop or when the for loop has
executed for the last value in sequence.
Question 11
In which cases, the else clause of a loop does not get executed?
Answer
The else clause of a loop does not get executed if the loop is terminated due to the execution
of a break statement inside the loop.
Question 12
Jump statements are used to unconditionally transfer program control to other parts within a
program. Python provides the below jump statements:
1. break
2. continue
Question 13
Answer
Sometimes the conditions being used in the code are complex and repetitive. In such cases, to
make the program more readable and maintainable, named conditions can be used.
Question 14
Answer
A loop which continues iterating indefinitely and never stops is termed as an endless or
infinite loop. Such loops can occur primarily due to two reasons:
1. Logical errors when the programmer misses updating the value of loop control
variable.
2. Purposefully created endless loops that have a break statement within their body to
terminate the loop.
Question 15
Answer
When the break statement gets executed, it terminates its loop completely and control reaches
to the statement immediately following the loop. The continue statement terminates only the
current iteration of the loop by skipping rest of the statements in the body of the loop.
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
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
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
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
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
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
⇒ 10 - 5 * 2
x-y*2
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 + i == 4:
print ("+", end = ' ')
else:
print ("o", end = ' ')
print()
Answer
Output
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 + i == 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.")
Question 1
Write a Python script that asks the user to enter a length in centimetres. If the user enters a
negative length, the program should tell the user that the entry is invalid. Otherwise, the
program should convert the length to inches and print out the result. There are 2.54
centimetres in an inch.
Solution
Output
A store charges ₹120 per item if you buy less than 10 items. If you buy between 10 and 99
items, the cost is ₹100 per item. If you buy 100 or more items, the cost is ₹70 per item. Write
a program that asks the user how many items they are buying and prints the total cost.
Solution
cost = 0
if n >= 100 :
cost = n * 70
elif n >= 10 :
cost = n * 100
else :
cost = n * 120
Output
Question 3
Write a program that reads from user — (i) an hour between 1 to 12 and (ii) number of hours
ahead. The program should then print the time after those many hours, e.g.,
Enter hour between 1-12 : 9
How many hours ahead : 4
Time at that time would be : 1 O'clock
Solution
s = hr + n
if s > 12:
s -= 12
Output
Question 4
Write a program that asks the user for two numbers and prints Close if the numbers are
within .001 of each other and Not close otherwise.
Solution
d = 0
if a > b :
d = a - b
else :
d = b - a
if d <= 0.001 :
print("Close")
else :
print("Not Close")
Output
Question 5
A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap
years unless they are also divisible by 400. Write a program that asks the user for a year and
prints out whether it is a leap year or not.
Solution
if year % 400 == 0 :
print(year, "is a Leap Year")
elif year % 100 == 0 :
print(year, "is not a Leap Year")
elif year % 4 == 0 :
print(year, "is a Leap Year")
else :
print(year, "is not a Leap Year")
Output
Question 6
Write a program to input length of three sides of a triangle. Then check if these sides will
form a triangle or not.
(Rule is: a+b>c;b+c>a;c+a>b)
Solution
Output
Question 7
Solution
if d == 0 :
print("Zero")
elif d == 1 :
print("One")
elif d == 2 :
print("Two")
elif d == 3 :
print("Three")
elif d == 4 :
print("Four")
elif d == 5 :
print("Five")
elif d == 6 :
print("Six")
elif d == 7 :
print("Seven")
elif d == 8 :
print("Eight")
elif d == 9 :
print("Nine")
else :
print("Invalid Digit")
Output
Enter a digit(0-9): 6
Six
Question 8
Write a short program to check whether square root of a number is prime or not.
Solution
import math
if c == 2 :
print("Square root is prime")
else :
print("Square root is not prime")
Output
Enter a number: 49
Square root is prime
Question 9
Solution
n = int(input("Enter n: "))
x = n * 2 - 1
Output
Enter n: 5
9
7
5
3
1
Question 10
Solution
print("First Series:")
for i in range(1, 41, 3) :
print(i, end = ' ')
print("\nSecond Series:")
x = 1
for i in range(1, 41, 3) :
print(i * x, end = ' ')
x *= -1
Output
First Series:
1 4 7 10 13 16 19 22 25 28 31 34 37 40
Second Series:
1 -4 7 -10 13 -16 19 -22 25 -28 31 -34 37 -40
Question 11
Write a short program to find average of list of numbers entered through keyboard.
Solution
sum = count = 0
print("Enter numbers")
print("(Enter 'q' to see the average)")
while True :
n = input()
if n == 'q' or n == 'Q' :
break
else :
sum += int(n)
count += 1
Output
Enter numbers
(Enter 'q' to see the average)
2
5
7
15
12
q
Average = 8.2
Question 12
Write a program to input 3 sides of a triangle and print whether it is an equilateral, scalene or
isosceles triangle.
Solution
if a == b and b == c :
print("Equilateral Triangle")
elif a == b or b == c or c == a:
print("Isosceles Triangle")
else :
print("Scalene Triangle")
Output
Write a program to take an integer a as an input and check whether it ends with 4 or 8. If it
ends with 4, print "ends with 4", if it ends with 8, print "ends with 8", otherwise print "ends
with neither".
Solution
if a % 10 == 4 :
print("ends with 4")
elif a % 10 == 8 :
print("ends with 8")
else :
print("ends with neither")
Output
Enter an integer: 18
ends with 8
Question 14
Write a program to take N (N > 20) as an input from the user. Print numbers from 11 to N.
When the number is a multiple of 3, print "Tipsy", when it is a multiple of 7, print "Topsy".
When it is a multiple of both, print "TipsyTopsy".
Solution
Output
Question 15
Write a short program to find largest number of a list of numbers entered through keyboard.
Solution
print("Enter numbers:")
print("(Enter 'q' to see the result)")
l = input()
Output
Enter numbers:
(Enter 'q' to see the result)
3
5
8
2
4
q
Largest Number = 8
Question 16
Write a program to input N numbers and then print the second largest number.
Solution
Output
Question 17
Given a list of integers, write a program to find those which are palindromes. For example,
the number 4321234 is a palindrome as it reads the same from left to right and from right to
left.
Solution
print("Enter numbers:")
print("(Enter 'q' to stop)")
while True :
n = input()
if n == 'q' or n == 'Q' :
break
n = int(n)
t = n
r = 0
while (t != 0) :
d = t % 10
r = r * 10 + d
t = t // 10
if (n == r) :
print(n, "is a Palindrome Number")
else :
print(n, "is not a Palindrome Number")
Output
Enter numbers:
(Enter 'q' to stop)
67826
67826 is not a Palindrome Number
4321234
4321234 is a Palindrome Number
256894
256894 is not a Palindrome Number
122221
122221 is a Palindrome Number
q
Question 18
(iii) form an integer Y that has the number of digits n at ten's place and the most significant
digit of X at one's place.
(iv) Output Y.
(For example, if X is equal to 2134, then Y should be 42 as there are 4 digits and the most
significant number is 2).
Solution
while temp != 0 :
digit = temp % 10
count += 1
temp = temp // 10
y = count * 10 + digit
print("Y =", y)
Output
Question 19
Write a Python program to print every integer between 1 and n divisible by m. Also report
whether the number that is divisible by m is even or odd.
Solution
m = int(input("Enter m: "))
n = int(input("Enter n: "))
for i in range(1, n) :
if i % m == 0 :
print(i, "is divisible by", m)
if i % 2 == 0 :
print(i, "is even")
else :
print(i, "is odd")
Output
Enter m: 3
Enter n: 20
3 is divisible by 3
3 is odd
6 is divisible by 3
6 is even
9 is divisible by 3
9 is odd
12 is divisible by 3
12 is even
15 is divisible by 3
15 is odd
18 is divisible by 3
18 is even
Question 20a
Solution
for i in range(7) :
t = n / d
sum += t * m
n += 3
d += 4
m *= -1
Output
Sum = 0.3642392586003134
Question 20b
12 + 32 + 52 + ..... + n2 (Input n)
Solution
i = 1
sum = 0
while i <= n :
sum += i ** 2
i += 2
Output
Enter the value of n: 9
Sum = 165
Question 21
Solution
for i in range(n + 1) :
fact = 1
for j in range(1, i) :
fact *= j
term = 1 / fact
sum += term
Output
Sum = 3.708333333333333
Question 22
Write a program to accept the age of n employees and count the number of persons in the
following age group:
(i) 26 - 35
(ii) 36 - 45
(iii) 46 - 55
Solution
for i in range(1, n + 1) :
age = int(input("Enter employee age: "))
#We have used chained comparison operators
if 26 <= age <= 35 :
g1 += 1
elif 36 <= age <= 45 :
g2 += 1
elif 46 <= age <= 55 :
g3 += 1
Output
Question 23a
Solution
sum = 0
m = 1
for i in range(1, 7) :
fact = 1
for j in range(1, i+1) :
fact *= j
term = x ** i / fact
sum += term * m
m = m * -1
Output
Question 23b
Solution
sum = 0
for i in range(1, n + 1) :
term = x ** i / i
sum += term
Output
Question 24a
*
**
***
**
*
Solution
n = 3 # number of rows
# upper half
for i in range(n) :
for j in range(n, i+1, -1) :
print(' ', end = '')
for k in range(i+1) :
print('*', end = ' ')
print()
# lower half
for i in range(n-1) :
for j in range(i + 1) :
print(' ', end = '')
for k in range(n-1, i, -1) :
print('*', end = ' ')
print()
Output
*
* *
* * *
* *
*
Question 24b
*
**
***
**
*
Solution
n = 3 # number of rows
# upper half
for i in range(n) :
for k in range(i+1) :
print('*', end = ' ')
print()
# lower half
for i in range(n-1) :
for k in range(n-1, i, -1) :
print('*', end = ' ')
print()
Output
*
* *
* * *
* *
*
Question 24c
*
* *
* *
* *
*
Solution
n = 3 # number of rows
# upper half
for i in range(1, n+1) :
# for loop for initial spaces
for j in range(n, i, -1) :
print(' ', end = '')
# lower half
for i in range(n-1, 0, -1) :
# for loop for initial spaces
for j in range(n, i, -1) :
print(' ', end = '')
Output
*
* *
* *
* *
*
Question 24d
*
**
* *
* *
* *
**
*
Solution
n = 4 # number of row
#upper half
for i in range(1, n+1) :
#while loop for * and spaces
x = 1
while x < 2 * i :
if x == 1 or x == 2 * i - 1 :
print('*', end = '')
else :
print(' ', end = '')
x += 1
print()
#lower half
for i in range(n-1, 0, -1) :
#while loop for * and spaces
x = 1
while x < 2 * i :
if x == 1 or x == 2 * i - 1 :
print('*', end = '')
else :
print(' ', end = '')
x += 1
print()
Output
*
* *
* *
* *
* *
* *
*
Question 25a
A
AB
ABC
ABCD
ABCDE
ABCDEF
Solution
n = 6
for i in range(n) :
t = 65
for j in range(i + 1) :
print(chr(t), end = ' ')
t += 1
print()
Output
A
A B
A B C
A B C D
A B C D E
A B C D E F
Question 25b
A
BB
CCC
DDDD
EEEEE
Solution
n = 5
t = 65
for i in range(n) :
for j in range(i + 1) :
print(chr(t), end = ' ')
t += 1
print()
Output
A
B B
C C C
D D D D
E E E E E
Question 25c
0
22
444
6666
88888
Solution
Output
0
2 2
4 4 4
6 6 6 6
8 8 8 8 8
Question 25d
2
44
666
8888
Solution
Output
2
4 4
6 6 6
8 8 8 8
Question 26
Write a program using nested loops to produce a rectangle of *'s with 6 rows and 20 *'s per
row.
Solution
for i in range(6) :
for j in range(20) :
print('*', end = '')
print()
Output
********************
********************
********************
********************
********************
********************
Question 27
Given three numbers A, B and C, write a program to write their values in an ascending order.
For example, if A = 12, B = 10, and C = 15, your program should print out:
Smallest number = 10
Next higher number = 12
Highest number = 15
Solution
Output
Question 28
Write a Python script to input temperature. Then ask them what units, Celsius or Fahrenheit,
the temperature is in. Your program should convert the temperature to the other unit. The
conversions are:
Solution
temp = float(input("Enter Temperature: "))
unit = input("Enter unit('C' for Celsius or 'F' for
Fahrenheit): ")
Output
Enter Temperature: 38
Enter unit('C' for Celsius or 'F' for Fahrenheit): C
Temperature in Fahrenheit = 100.4
Question 29
Ask the user to enter a temperature in Celsius. The program should print a message based on
the temperature:
If the temperature is less than -273.15, print that the temperature is invalid because it
is below absolute zero.
If it is exactly -273.15, print that the temperature is absolute 0.
If the temperature is between -273.15 and 0, print that the temperature is below
freezing.
If it is 0, print that the temperature is at the freezing point.
If it is between 0 and 100, print that the temperature is in the normal range.
If it is 100, print that the temperature is at the boiling point.
If it is above 100, print that the temperature is above the boiling point.
Solution
Output
Question 30
Write a program to display all of the integers from 1 up to and including some integer entered
by the user followed by a list of each number's prime factors. Numbers greater than 1 that
only have a single prime factor will be marked as prime.
For example, if the user enters 10 then the output of the program should be:
Solution
import math
for i in range(1, n + 1) :
if i == 1:
print("1 = 1")
else :
print(i, "=", end=' ')
c = 0
for j in range(1, i + 1) :
if i % j == 0:
c += 1
if c == 2:
print(i, "(prime)", end = '')
print()
else :
t = i
while t % 2 == 0 :
print("2", end='x')
t = t // 2
k = 3
x = math.ceil(math.sqrt(t)) + 1
while k <= x :
while (t % k == 0) :
print(k, end='x')
t = t // k
k += 2
if t > 2 :
print(t, end='x')
print()
Output
Enter an integer: 10
1 = 1
2 = 2 (prime)
3 = 3 (prime)
4 = 2x2x
5 = 5 (prime)
6 = 2x3x
7 = 7 (prime)
8 = 2x2x2x
9 = 3x3x
10 = 2x5x