You are on page 1of 55

Python Programming

Unit 2 – Part 2
Book Back Exercises (Answers)
Text Book: Computer Science with Python, Sumitha Arora, 9th Edition, 2019
CHAPTER – 8 (Conditional and Iterative Statements)
Check Point 8.1 (Chapter 8) – Pg.216
Q.NO. PAGE NO.
1-3 214
4-5 215

Programs 8.1 to 8.20


P.NO. PAGE NO.
8.1 221
8.2-8.3 222
8.4-8.5 224
8.6 225
8.7 227
8.8-8.9 229
8.10 230
8.11 238
8.12-8.13 239
8.14-8.15 243
8.16 245
8.17 248
8.18-8.19 251
8.20 255

Check Point 8.2 (Chapter 8) – Pg.231


Q.NO. PAGE NO.
1-2 218
Q.NO.3.
Correct the following code fragment:
if(x=1)
k=100
1
else
k=10
Answer: (Corrected Code)
if(x==1):
k=100
else:
k=10
Q.NO.4.
What will be the output of following code fragment if the input given is (i) 7 (ii) 5?
a=input('Enter a number')
if(a==5):
print("Five")
else:
print("Not Five")
Output:
If the input given is (i) 7 If the input given is (ii) 5
Enter a number7 Enter a number5
Not Five Not Five
Reason: Value of a is received as string since it is not Reason: Value of a is received as string since it is not
type casted into integer. Hence ‘7’ is not equal to 5. type casted into integer. Hence ‘5’ is not equal to 5
Q.NO.5.
What will be the output of following code fragment if the input given is (i) 2000 (ii) 1900 (iii) 1971 ?
year=int(input('Enter 4-digit year'))
if(year%100==0):
if(year%400==0):
print("LEAP century year")
else:
print("Not century year")
Output:
If the input given is (i) 2000 If the input given is (ii) 1900 If the input given is (iii) 1971
Enter 4-digit year2000 Enter 4-digit year1900 Enter 4-digit year1971
LEAP century year <Nothing is displayed> Not century year
Reason: 2000%100=0 and Reason: 1900%100=0 and Reason: 1971%100=71
2000%400=0 1900%400=300 1971%400=371

2
Q.NO.5.
What will be the output of following code fragment if the input given is (i) 2000 (ii) 1900 (iii) 1971 ?
year=int(input('Enter 4-digit year'))
if(year%100==0):
if(year%400==0):
print("LEAP century year")
else:
print("Not century year")
Output:
If the input given is (i) 2000 If the input given is (ii) 1900 If the input given is (iii) 1971
Enter 4-digit year2000 Enter 4-digit year1900 Enter 4-digit year1971
LEAP century year Not century year <Nothing is displayed>
Reason: 2000%100=0 and Reason: 1900%100=0 and Reason: 1971%100=71
2000%400=0 1900%400=300 1971%400=371

Check Point 8.3 (Chapter 8) – Pg.253, 254


Q.NO. PAGE NO.
1-2 236
Q.NO.3.
What is the use of range() function? What would range (3,13) return?
Answer:
The range() function of Python generates a list which is a special sequence type. A sequence in Python Is a
succession of values bound together by a single name. Some Python sequence types are: strings, lists,
tuples etc.,
Syntax: range(<lower limit>,<upper limit>)
range (3,13) would return the following sequence of numbers 3,4,…..,12.
Q.NO.4.
What is the output of the following code fragment?
for a in "abcde":
print(a,'+',end=' ')
Output:
a+b+c+d+e+
Q.NO.5.
What is the output of the following code fragment?
for i in range(0,10):
3
pass
print(i)
Output:
9
Q.NO.6.
Why does “Hello” not print even once?
for i in range(10,1):
print("Hello")
Output:
<Nothing will be displayed>
Reason:
This returns an empty sequence, since the default step value is +1 as no number falls in the Arithmetic
Progression (A.P) beginning with 10 and ending with 1.
Q.NO.7.
What is the output of the following code?
for a in range(2,7):
for b in range(1,a):
print(' #',end=' ')
print( )
Output:
#
# #
# # #
# # # #
# # # # #
Q.NO.8.
Write a for loop that displays that even numbers from 51 to 60.
Program Coding: (Simple and One possible Solution)
print("Even numbers from 51 to 60 are as follows:")
for a in range(52,62,2):
print(a)
Output:
Even numbers from 51 to 60 are as follows:
52
54
4
56
58
60
Q.NO.9.
Suggest a situation when an empty loop is useful.
Answer: An empty loop is a do-nothing loop that doesn't contain any executable statement (whereas, an infinite
loop is a loop that runs an infinite number of times.)
One situation when an empty loop is useful is when purposely the runtime of the Program need to be delayed. (i.e)
to produce time-breaks
Q.NO.10.
What is the similarity and difference between for and while loop?
Answer:
Similarities:
 Both are iterative or repetition or looping statements
 Both allow a set of instructions to be performed repeatedly until a certain condition is fulfilled
 Both get iterated over a list of values
 Both have conditions and an iterative variable with the count for iterations
 else - clause can be used for both these loops
Differences:
for loop while loop
It is used when the number of iterations are known It is used when the number of iterations are decided
in advance only based on meeting out the condition
The for statement iterates through a collection or The while statement simply loops until a condition is
iterable object or generator function False
This is an Exit Controlled Loop This is an Entry Controlled Loop
This is called as a Counting Loop This is called as a Conditional Loop
Q.NO.11.
Why is while loop called an entry controlled loop?
Answer: The control moves into the loop only when the condition/test expression mentioned in while loop
gets satisfied (i.e) the entry is decided only on the basis of true state of the condition. Hence, while loop is
called an entry controlled loop
Q.NO.12.
If the test expression of a while loop evaluates to false in the beginning of the loop, even before entering
into the loop:
(a) how many times is the loop executed?
Answer: Not even one time
5
(b) how many times is the loop-else clause executed?
Answer: Only once
Q.NO.13.
What will be the output for the following code?
while(6+2>8):
print("Gotcha!")
else:
print("Going out!")
Output:
Going out!
Q.NO.14.
What is the output produced by the following loop?
for a in (2,7):
for b in (1,a):
print(b, end=' ')
print()
Output:
1
2
1
7
Q.NO. PAGE NO.
15 244,246
16 244
Solved Problems (Chapter 8) – Pg.256
Q.NO. PAGE NO.
1-2 256
3-6 257
7-9 258
10-12 259
13-14 260
15-18 261
19-21 262
22-25 263
26-27 264

6
Type A : Short Answer Questions/Conceptual Questions (Page: 264)
Q.NO. PAGE NO.
1 214
2 215
3-4 214
5-6 217
Q.NO.7.
Draw Flowchart for displaying first 10 odd numbers.
Answer: Start

Assign i=0

True
Whether
i<=10?

False
False
Whether
i%2==0?

True

Print i

Compute
i=i+1

Stop
Q.NO.8.
What is an entry-controlled loop?
Answer: An entry controlled loop is a type of loop in which the condition is checked first and then after the
loop body executed. If the test condition is true, the loop body would be executed otherwise, the loop
would be terminated. In Python, the entry controlled loop is while.
Q.NO. PAGE NO.
9 241
10 243-244
11-12 244
13 231
14 242

7
Type B : Application Based Question (Page: 265)
Q.NO.1.
Rewrite the following code fragment that saves on the number of comparisons
Given Code Rewritten Code (Answer)
if(a==0): if(a==0):
print(“Zero”) print(“Zero”)
if(a==1): elif(a==1):
print(“One”) print(“One”)
if(a==2): elif(a==2):
print(“Two”) print(“Two”)
if(a==3): elif(a==3): (or) else:
print(“Three”) print(“Three”)
Q.NO.2.
Under what conditions will this code fragment print “water”?
if temp<32:
print(“ice”)
elif temp<212:
print(“water”)
else:
print(“steam”)
Answer: Under the conditions when temp value gets the value within the range of 33 to 211, this code
fragment print “water”. Note: temp=int(input()) in the 1st line
Q.NO.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")
Output:
CD

8
Q.NO.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")
Corrected Code: (equal to operator should be used instead of assignment operator with in if condition)
weather='raining'
if weather=='sunny':
print("wear sunblock")
elif weather=='snow':
print("going skiing")
else:
print("weather")
Output for the Corrected Code: weather
Q.NO.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")
Output:
ValueError: invalid literal for int() with base 10: 'zero'
Since it got stuck up with the error at initial condition, it could not proceed further.
Note:
 int('zero') - produces ValueError: invalid literal for int() with base 10: 'zero'
 str(0) = ‘0’

9
Q.NO.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")
Corrected Code:
if n==0: (colon added)
print("zero")
elif n==1: (colon position changed)
print("one")
elif n==2: (statements are merged properly)
print("two")
elif n==3: (else is replaced by elif)
print("three")
Note: n=int(input()) in the 1st line
Q.NO.7.
What is the following code doing? What would it print for input as 3?
Program Coding:
n=int(input("Enter an integer:"))
if n<1:
print("invalid value")
else:
for i in range(1,n+1):
print(i*i)
Working:
(i) An integer number is got from the user(say n)
(ii) If the n value is less than 1, “invalid value” is printed using the ‘if’ part
(iii) In the else part, a ‘for’ loop is initialized with a range of (1, n+1), then it is multiplied to itself
Eg: If user enters 3, range is (1,4) that comes with the values: 1,2,3
(iv) The control comes out of the ‘for’ loop when the last value of the sequence in ‘for’ is reached

10
Output:
Enter an integer:3
1
4
9
Q.NO.8.
How are the following two code fragments different from one another? Also predict the output of the
following code fragments?
(a) (b)
n=int(input("Enter an integer:")) n=int(input("Enter an integer:"))
if n>0: if n>0:
for a in range(1,n+n): for a in range(1,n+n ):
print(a/(n/2)) print(a/(n/2))
else: else:
print("Now quiting") print("Now quiting")
Difference: The indentation of ‘else’ makes the difference. In the code fragment (a), the else clause is ‘for-
else’, whereas in the code fragment (b), the else clause is ‘if-else’. This is the reason for changes in output.
Output: Output:
Enter an integer:5 Enter an integer:5
0.4 0.4
0.8 0.8
1.2 1.2
1.6 1.6
2.0 2.0
2.4 2.4
2.8 2.8
3.2 3.2
3.6 3.6
Now quiting
Q.NO.9.
Rewrite the following code fragments using for loop.
(a) (b) (c)
i=100 num=int(input("Enter num value:")) num=int(input("Enter num value:"))
while(i>0): while num>0: count=sum=0
print(i) print(num%10) while num>0:
i-=3 num=num/10 count+=1
sum+=num
num-=2
if count==10:
print(sum/float(count))
break

11
Rewritten code (using for)
(a) (b) (c)
for i in range(100,0,-3): It is not advisable to work with infinite loops like this in ‘for’ since the number of
print(i) iterations are not known in advance.
from itertools import cycle sum=0
a = cycle([0]) num=int(input("Enter the value of
num=int(input("Enter the value of num:"))
num:")) if num>0:
for i in a: for count in range(num,sum,-1):
if num>0: sum+=num
print(num%10) num-=2
num=num/10 if count==10:
print(sum/float(count))
break
Output: Output: Output:
100 Enter the value of num:3 Enter num value:100
97
3 91.0
94
…………..to……………… 0.3
16 0.03
13
…………..to………………
10
7 3e-323
4
5e-324
1

Q.NO.10.
Rewrite the following code fragments using while loops:
(a) (b) (c)
num=int(input("Enter the num value:")) for i in range(1,16): for i in range(4):
min=sum=0 if i%3==0: for j in range(5):
max=num print(i) if i+1==j or j+i==4:
if num<0:
print("+", end=' ')
min=num
else:
max=0
print("o", end=' ')
for i in range(min,max+1):
print()
sum+=i
print(sum)

12
Rewritten code (using while)
(a) (b) (c)
num=int(input("Enter the num value:")) i=1 i=0
min=sum=0 while (i<16): while(i<4):
max=num if i%3==0: j=0
if num<0:
print(i) while(j<5):
min=num
i+=1 if i+1==j or j+i==4:
max=0
print("+", end=' ')
while num>=min and num<=max:
j=j+1
sum+=num
else:
num+=1
print(sum) print("o", end=' ')
i=i+1
print()
Output: Output: Output:
Enter the num value:-3 3 ++o++o++o++o
-6 6
9
12
15
Q.NO.11.
Predict the output of the following code fragments:
a b c
count=0 x=10 keepgoing=True
while count<10: y=0 x=100
print("Hello") while x>y: while keepgoing:
count+=1 print(x,y) print(x)
x=x-1 x=x-10
y=y+1 if x<50:
keepgoing=False
Output (a) Output (b) Output (c)
Hello 10 0 100
Hello 9 1 90
Hello 8 2 80
Hello 7 3 70
Hello 6 4 60
Hello 50
Hello
Hello
Hello
Hello

13
d e f
x=45 for x in [1,2,3,4,5]: for x in range(5):
while x<50: print(x) print(x)
print(x)
Output (d) Output (e) Output (f)
Endless loop that displays 45 1 0
repeatedly one after the other 2 1
3 2
4 3
5 4
g h i
for p in range(1,10): for q in range(100,50,-10): for z in range(-500,500,100):
print(p) print(q) print(z)
Output (g) Output (h) Output (i)
1 100 -500
2 90 -400
3 80 -300
4 70 -200
5 60 -100
6 0
7 100
8 200
9 300
400
j k l
for y in range(500,100,100): x=10 for x in [1,2,3]:
print(" * ",y) y=5 for y in [4,5,6]:
for y in range(x-y * 2): print(x,y)
print(" % ",i)
Output (j) Output (k) Output (l)
Nothing will be displayed Nothing will be displayed 14
15
(Since Step value is not (Since the range value becomes 0) 16
decremented) 24
25
26
34
35
36
m n
for x in range(3): c=0
for y in range(4): for x in range(10):
print(x,y,x+y) for y in range(5):
c+=1
print(c)
Output (m) Output (n)
000 5
011 10
022 15
033 20
101 25
112 30
123 35
134 40
202 45
213 50
224
235

14
Q.NO.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+i==4:
print("+",end=' ')
else:
print("o",end=' ')
print()
Output:
o+oo+oo++ooo++oo+oo+ #In a single line
Q.NO.13.
In the nested for loop code above (Q.12), how many times is the condition of the if clause evaluated?
Answer: 10 times
Q.NO.14.
Which of the following Python programs implement the control flow graph shown?

True

true

n=int(input(…))

false false true


n==A2 n==A1
print(“what”) continue
true

break

print(“ever”)

a b c
while True: while True: while True:
n=int(input("Enter an int:")) n=int(input("Enter an int:")) n=int(input("Enter an int:"))
if n==A1: if n==A1: if n==A1:
continue continue continue
elif n==A2: elif n==A2: elif n==A2:
break break break
else: else: print("what")
print("what") print("what") print("ever")
else: print("ever")
print("ever")
Answer: Option (b), it matches the control flow graph correctly.
Reason for the mismatch of other options: In Option ‘a’, else clause will not be executed during abnormal
termination of the loop. In Option ‘c’, “what” and “ever” comes as sequence statements which is different
from the flow graph.
15
Type C : Programming Practice/Knowledge Based Questions (Chapter 8) (Pg.268)
Q.NO.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.
Program Coding:
length=int(input("Enter the length (in cms):"))
if length<0:
print("Entry is Invalid")
else:
inch=length/2.54
print("Length conversion result (in inches):",round(inch,4))
Output:
Enter the length (in cms):-56 Enter the length (in cms):14
Entry is Invalid Length conversion result (in inches): 5.5118

Q.NO.2
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.
Program Coding: (Note: Here ‘between’ is considered to be inclusive)
items=int(input("Enter how many items you want to buy:"))
if items<10:
price=items*120
print("The Cost per item is: Rs.120")
print("The Total Cost is: Rs.", price)
elif items>=10 and items<=99:
price=items*100
print("The Cost per item is: Rs.100")
print("The Total Cost is: Rs.", price)
elif items>=100:
price=items*70
print("The Cost per item is: Rs.70")
print("The Total Cost is: Rs.", price)

16
Output:
Enter how many items you want Enter how many items you want Enter how many items you want
to buy:5 to buy:24 to buy:102
The Cost per item is: Rs.120 The Cost per item is: Rs.100 The Cost per item is: Rs.70
The Total Cost is: Rs. 600 The Total Cost is: Rs. 2400 The Total Cost is: Rs. 7140
Q.NO.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
Program Coding:
hours=int(input("Enter hour between 1-12: "))
hours_ahead=int(input("How many hours ahead?: "))
a=hours+hours_ahead
if a<=12:
time=a
print("Time at that time would be :", time,"o’clock")
else:
time=a-12
print("Time at that time would be :", time,"o’clock")
Output:
Enter hour between 1-12: 8 Enter hour between 1-12: 9
How many hours ahead?: 4 How many hours ahead?: 4
Time at that time would be : 12 o’clock Time at that time would be : 1 o’clock
Q.NO.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.
Program Coding:
num1=float(input("Enter the 1st float number(with 3 decimals):"))
num2=float(input("Enter the 2nd number(with 3 decimals):"))
diff=round(num1-num2,3)
if(diff==0.001):
print("Close","The difference is:",diff)
else:
print("Not Close","The difference is:",diff)
17
Output:
Enter the 1st float number(with 3 decimals):23.005 Enter the 1st float number(with 3 decimals):23.005
Enter the 2nd number(with 3 decimals):23.004 Enter the 2nd number(with 3 decimals):23.003
Close. The difference is: 0.001 Not Close. The difference is: 0.002
Q.NO.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.
Program Coding:
def leap(y):
if(y%400==0):
print("It's a leap year")
elif(y%100==0):
print("It's not a leap year")
elif(y%4==0):
print("It's a leap year")
else:
print("It's not a leap year")
year=int(input("Enter the year:"))
leap(year)
Output:
Enter the year:2019 Enter the year:2020
It's not a leap year It's a leap year
Q.NO.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)
Program Coding:
a=int(input("Enter side1 of a Triangle:"))
b=int(input("Enter side2 of a Triangle:"))
c=int(input("Enter side3 of a Triangle:"))
if(a+b>c and b+c>a and c+a>b):
print("These 3 sides can form a triangle")
else:
print("These 3 sides cannot form a triangle")

18
Output:
Enter side1 of a Triangle:2 Enter side1 of a Triangle:1
Enter side2 of a Triangle:3 Enter side2 of a Triangle:0
Enter side3 of a Triangle:4 Enter side3 of a Triangle:1
These 3 sides can form a triangle These 3 sides cannot form a triangle
Q.NO.7
Write a short program to input a digit and print it in words.
Program Coding:
a=int(input("Enter a digit [0 to 9]:"))
dict={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine"}
if a in dict:
print(dict[a])
Output:
Enter a digit [0 to 9]:3
Three
Q.NO.8
Write a short program to check whether square root of a number is prime or not.
Program Coding:
import math
a=int(input("Enter a Number:"))
b=int(math.sqrt(a)) #Prime number can't be a decimal number
i=b-1
if(i>1):
for i in range(2,b//2):
if(b%i==0):
print("The Sqrt of the no. is not a Prime")
break
else:
print("The Sqrt of the no. is Prime")
else:
print("Invalid!")
Output:
Enter a Number:9 Enter a Number:38 Enter a Number:2
The Sqrt of the no. is Prime The Sqrt of the no. is not a Prime Invalid!

19
Q.NO.9
Write a short program to find first n odd numbers in descending order.
Program Coding:
n=int(input("Enter a Number:"))
for i in range(n-1,-1,-1):
a=1+i*2
print(a,end=" ")
Output:
Enter a Number:15
29 27 25 23 21 19 17 15 13 11 9 7 5 3 1
Q.NO.10
Write a short program to print the following series: (i) 1 4 7 10 ……….. 40 (ii) 1 -4 7 -10 ……….. -40
Program Coding:
(i) (ii)
for i in range(1,42,3): for i in range(1,42,3):
print(i,end=" ") if(i%2!=0):
print(i,end=" ")
else:
print(-i,end=" ")
Output: <As given in the question>
Q.NO.11
Write a short program to find average of list of numbers entered through keyboard.
Program Coding:
import statistics
l=[]
n=int(input("Enter the no. of values you want to enter:"))
for i in range(n):
print("Enter the element",i+1,": ",end="")
a=int(input())
l.append(a)
print("The average of list of numbers is:",statistics.mean(l))
Output:
Enter the no. of values you want to enter:5
Enter the element 1 : 6
Enter the element 2 : 7
Enter the element 3 : 8
Enter the element 4 : 9
Enter the element 5 : 10
The average of list of numbers is: 8
20
Q.NO.12
Write a program to input 3 sides of a triangle and print whether it is an equilateral, scalene or isosceles
triangle.
Program Coding:
Note: Equilateral (All 3 sides are equal), Scalene (No sides are equal), Isosceles triangle (Any 2 sides are equal).
a=int(input("Enter side1 of a Triangle:"))
b=int(input("Enter side2 of a Triangle:"))
c=int(input("Enter side3 of a Triangle:"))
if a==b==c:
print("These 3 sides can form a Equilateral triangle")
elif a==b or b==c or c==a:
print("These 3 sides can form a Isosceles triangle")
else:
print("These 3 sides can form a Scalene triangle")
Output:
Enter side1 of a Triangle:10 Enter side1 of a Triangle:10 Enter side1 of a Triangle:10
Enter side2 of a Triangle:10 Enter side2 of a Triangle:20 Enter side2 of a Triangle:10
Enter side3 of a Triangle:10 Enter side3 of a Triangle:30 Enter side3 of a Triangle:20
These 3 sides can form a These 3 sides can form a Scalene These 3 sides can form a Isosceles
Equilateral triangle triangle triangle
Q.NO.13
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”.
Program Coding:
a=int(input("Enter a Number: "))
last_digit=a%10
if(last_digit==4):
print("Ends with 4")
elif(last_digit==8):
print("Ends with 8")
else:
print("Ends with Neither")
Output:
Enter a Number: 214 Enter a Number: 218 Enter a Number: 210
Ends with 4 Ends with 8 Ends with Neither

21
Q.NO.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”.
Program Coding:
N=int(input("Enter a Number greater than 20: "))
if N>20:
for i in range(11,N+1):
if(i%3==0):
print(i,"Tipsy")
elif(i%7==0):
print(i,"Topsy")
else:
print(i,"TipsyTopsy")
else:
print("Number is not greater than 20")
Output:
Enter a Number greater than 20: 21 Enter a Number greater than 20: 19
11 TipsyTopsy Number is not greater than 20
12 Tipsy
13 TipsyTopsy
14 Topsy
15 Tipsy
16 TipsyTopsy
17 TipsyTopsy
18 Tipsy
19 TipsyTopsy
20 TipsyTopsy
21 Tipsy
Q.NO.15
Write a short program to find largest number of a list of numbers entered through keyboard.
Program Coding:
l=[]
n=int(input("Enter the no. of values you want to enter:"))
for i in range(n):
print("Enter the element",i+1,": ",end="")
a=int(input())
l.append(a)
print("The largest number of the list of numbers is:",max(l))
22
Output:
Enter the no. of values you want to enter:5
Enter the element 1 : 10
Enter the element 2 : 20
Enter the element 3 : 30
Enter the element 4 : 40
Enter the element 5 : 50
The largest number of the list of numbers is: 50
Q.NO.16
Write a program to input N numbers and then print the second largest number.
Program Coding:
l=[]
n=int(input("Enter the no. of values you want to enter:"))
for i in range(n):
print("Enter the element",i+1,": ",end="")
a=int(input())
l.append(a)
l.sort()
for i in range(n):
if (l[n-(i+1)]!=l[n-(i+2)]): #To handle repetitive numbers
print("The Second largest number of the list of numbers is:",l[n-(i+2)])
break
Output:
Enter the no. of values you want to enter:5 Enter the no. of values you want to enter:5
Enter the element 1 : 30 Enter the element 1 : 30
Enter the element 2 : 20 Enter the element 2 : 20
Enter the element 3 : 10 Enter the element 3 : 10
Enter the element 4 : 50 Enter the element 4 : 50
Enter the element 5 : 40 Enter the element 5 : 50
The Second largest number of the list of numbers is: The Second largest number of the list of numbers is:
40 30
Q.NO.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.

23
Program Coding:
n=int(input("Enter a number:"))
m=n #Since n value will change in between
rev=0
while(n>0):
remainder=n%10
rev=(rev*10)+remainder
n=n//10
if m==rev:
print("Entered no.is a Palindrome")
else:
print("Entered no.is not a Palindrome")
Output:
Enter a number: 4321234 Enter a number: 21546
Entered no.is a Palindrome Entered no.is not a Palindrome
Q.NO.18
Write a complete Python program to do the following:
(i) read an integer X.
(ii) determine the number of digits n in X.
(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)
Program Coding:
X=int(input("Enter a number:"))
count=remainder=0
while(X>0):
remainder=X%10
count=count+1
X=X//10
Y=str(count)+str(remainder)
print("The Output Y: ",int(Y))
Output:
Enter a number:2134
The Output Y: 42

24
Q.NO.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.
Program Coding:
n=int(input("Enter the n value: "))
m=int(input("Enter the divisor: "))
for i in range(1,n+1):
if i%m==0 and i%2==0:
print(i,"is divisible by",m, "and", i, "is an even number")
elif i%m==0 and i%2!=0:
print(i,"is divisible by",m, "and", i, "is an odd number")
else:
print(i,"is not divisible by",m)
Output:
Enter the n value: 10
Enter the divisor: 3
1 is not divisible by 3
2 is not divisible by 3
3 is divisible by 3 and 3 is an odd number
4 is not divisible by 3
5 is not divisible by 3
6 is divisible by 3 and 6 is an even number
7 is not divisible by 3
8 is not divisible by 3
9 is divisible by 3 and 9 is an odd number
10 is not divisible by 3
Q.NO.20
Write Python programs to sum the given sequences:

a)

b) 12 + 32 + 52 + ………..+n2 (Input n)
Program Coding:
a)
l1=[]
l2=[] #Don’t use l1=l2=[] in single line since the values will be appended on a single list
sum1=sum2=0
for a in range(2,21,3):
l1.append(a)
for b in range(9,34,4):
25
l2.append(b)
print("List1:",l1,"List2:",l2)
for i in range(7):
if i%2==0:
sum1=sum1+l1[i]/l2[i]
else:
sum2=sum2+l1[i]/l2[i]
sum=sum1-sum2
print("The result of the sequence: ",round(sum,4))
b)
n=int(input("Enter the n value: "))
sum=0
for a in range(1,n+1,2):
sum=sum+a**2
print(a)
print("Sum of Squares: ",sum)
Output:
(a) (b)
List1: [2, 5, 8, 11, 14, 17, 20] List2: [9, 13, 17, 21, 25, 29, 33] Enter the n value: 5
The result of the sequence: 0.3642 1
3
5
Sum of Squares: 35
Q.NO.21
Write a Python program to sum the sequence:

Program Coding:
fact=1
sum=1
n=int(input("Enter the n value:"))
for i in range(1,n+1):
fact*=i
sum+=1/fact
print("Sum of reciprocal of factorial series:",round(sum,4))

26
Output:
Enter the n value:6
Sum of reciprocal of factorial series: 2.7181
Q.NO.22
Write a Python 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
Program Coding:
l=[]
count1=count2=count3=0
n=int(input("Enter the no. of employees(from 26 to 55):"))
for i in range(n):
print("Enter the age of employee",i+1,": ",end="")
a=int(input())
l.append(a)
l.sort()
for i in range(len(l)):
if l[i]>=26 and l[i]<=35:
count1+=1
elif l[i]>=36 and l[i]<=45:
count2+=1
elif l[i]>=46 and l[i]<=55:
count3+=1
print("The no. of persons in Group1 (Age:26-35) is:",count1)
print("The no. of persons in Group2 (Age:36-45) is:",count2)
print("The no. of persons in Group3 (Age:46-55) is:",count3)
Output:
Enter the no. of employees(from 26 to 55):5
Enter the age of employee 1 : 26
Enter the age of employee 2 : 31
Enter the age of employee 3 : 32
Enter the age of employee 4 : 48
Enter the age of employee 5 : 55
The no. of persons in Group1 (Age:26-35) is: 3
The no. of persons in Group2 (Age:36-45) is: 0
The no. of persons in Group3 (Age:46-55) is: 2

27
Q.NO.23
Write a Python program to find the sum of the following series:

(a)

(b)

Program Coding:
(a) (b)
fact=1 sum=0
sum1=sum2=0 x=int(input("Enter the x value:"))
x=int(input("Enter the x value:")) n=int(input("Enter the n value:"))
for i in range(1,7): for i in range(1,n+1):
fact*=i sum=sum+(x**i/i)
if i%2!=0: print("Sum of the series:",round(sum,4))
sum1=sum1+(x**i/fact)
else:
sum2=sum2+(x**i/fact)
sum=sum1-sum2
print("Sum of the series:",round(sum,4))
Output:
(a) (b)
Enter the x value:2 Enter the x value:2
Sum of the series: 0.8444 Enter the n value:6
Sum of the series: 27.7333
Q.NO.24
Write Python programs to print the following shapes:
(a) (b) (c) (d)
* * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * *
* *
*
Program Coding:
(a)
for i in range(5):
for j in range(5):

28
if(i==2 and j%2==0) or ((i==1 or i==3)and j%2!=0) or ((i==0 or i==4)and j==2):
print("*",end=" ")
else:
print(" ",end=" ")
print()
(b)
for i in range(5):
for j in range(5):
if(i==2 and j%2==0) or ((i==1 or i==3)and j%2!=0) or ((i==0 or i==4)and j==2):
print("*",end="")
else:
print("",end="") #Same as previous but space is removed
print()
Outputs: <As given in the question>
Q.NO.25
Write Python programs using nested loops to produce the following patterns:
(a) (b) (c) (d)
A A 0 2
A B B B 2 2 4 4
A B C C C C 4 4 4 6 6 6
A B C D D D D D 6 6 6 6 8 8 8 8
A B C D E E E E E E 8 8 8 8 8
A B C D E F F F F F F F
Program Coding:
(a)
a=65
for i in range(6):
for j in range(i+1):
print(chr(a+j),end=" ")
else:
print(" ",end=" ")
print()
(b)
a=65
for i in range(5): #Same as previous-Range is reduced
for j in range(i+1):
print(chr(a+i),end=" ") #Same as previous-i is replaced by j
29
else:
print(" ",end=" ")
print()
(c)
for i in range(5):
for j in range(i+1):
print(i*2,end=" ")
else:
print(" ",end=" ")
print()
(d)
for i in range(4):
for j in range(i+1):
print((i+1)*2,end=" ") #Same as previous - (i is replaced by i+1)
else:
print(" ",end=" ")
print()
Outputs: <As given in the question>
Q.NO.26
Write a Program using nested loops to produce a rectangle of *’s with 6 rows and 20 *’s per row.
Program Coding:
for i in range(6):
for j in range(20):
print("*",end=" ")
print()
Output:
********************
********************
********************
********************
********************
********************
Q.NO.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:

30
Smallest Number = 10
Next Highest Number = 12
Highest Number = 15
Program Coding:
A=int(input("Enter the A value: "))
B=int(input("Enter the B value: "))
C=int(input("Enter the C value: "))
x=[A,B,C]
x.sort()
print("Smallest number=",x[0])
print("Next higher number=",x[1])
print("Highest number=",x[2])
Output:
Enter the A value: 25
Enter the B value: 65
Enter the C value: 45
Smallest number= 25
Next higher number= 45
Highest number= 65
Q.NO.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
F=9/5C+32 and C=5/9(F32).
Program Coding:
tem=int(input("Enter the Temperature:"))
choice=input("Enter C or c for Celsius/ F or f for Fahrenheit:")
if(choice=='C' or choice=='c'):
C=tem
F=(9/5)*C+32
print("The Temperature (in Fahrenheit):",F)
elif(choice=='F' or choice=='f'):
F=tem
C=5/9*(F-32)
print("The Temperature (in Celsius):",C)
else:
print("Invalid Choice!")

31
Output:
Enter the Temperature: 40 Enter the Temperature: 41
Enter C or c for Celsius/ F or f for Fahrenheit: C Enter C or c for Celsius/ F or f for Fahrenheit: F
The Temperature (in Fahrenheit): 104.0 The Temperature (in Celsius): 5.0

Q.NO.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.
Program Coding:
tem=float(input("Enter the Temperature (in Celsius):"))
if(tem<-273.15):
print("Temperature is Invalid, because it is below absolute zero")
elif(tem==-273.15):
print("Temperature is absolute zero")
elif(tem>-273.15 and tem<0): #Here between is considered as exclusive
print("Temperature is below freezing")
elif(tem==0):
print("Temperature is at the freezing point")
elif(tem>0 and tem<100):
print("Temperature is at the freezing point")
elif(tem==100):
print("Temperature is at the boiling point")
else:
print("Temperature is above the boiling point")
Output:
Enter the Temperature (in Celsius):-274.15 Enter the Temperature (in Celsius):0
Temperature is Invalid, because it is below absolute zero Temperature is at the freezing point
Enter the Temperature (in Celsius):-273.15 Enter the Temperature (in Celsius):100
Temperature is absolute zero Temperature is at the boiling point
Enter the Temperature (in Celsius):-270.15 Enter the Temperature (in Celsius):103
Temperature is below freezing Temperature is above the boiling point

32
CHAPTER – 9 (String Manipuation)
Check Point 9.1 (Chapter 9) – Pg.280
Q.NO.1.
How are strings internally stored?
Answer: Python strings are immutable and are stored internally as a sequence of characters, where each
character has a unique position id/ index beginning from 0 to (length-1) in forward direction and backward
from -1,-2,…….,-length.
Q.NO.2.
For a string s storing ‘Goldy’, what would s[0] and s[-1] return?
Answer:
>>> s='Goldy'
>>> s[0] 'G'
>>> s[-1] 'y'
Q.NO.3.
The last character of a string s is at index len(s)-1. True / False?
Answer: True
>>> s[len(s)-1] 'y'
Q.NO.4.
For strings, + means (1) ; * means (2). Suggest words for positions (1) and (2).
Answer: (1) Replication (2) Concatenation
Q.NO.5.
Given that s1 = “spam”, s2 = “ni!”. What is the output produced by following expressions?
(a) “ The Kinghts who say, “ + s2 (b) 3 * s1 + 2 * s2 (c) s1[1]
Answers: (a),(b),(c)
>>> s1 = "spam"
>>> s2 = "ni!"
>>> " The Kinghts who say, " + s2 ' The Kinghts who say, ni!'
>>> 3 * s1 + 2 * s2 'spamspamspamni!ni!'
>>> s1[1] 'p'
Q.NO. PAGE NO.
6 Pg.276
7 Pg.277
Q.NO.8.
What will be the result of following expressions?

33
(a) “Wow Python”[1] (b) “Strings are fun.”[5] (c) len(“awesome”)
(d) “Mystery”[:4] (e) “apple” > “pineapple” (f) “pineapple” < “Peach”
(g) “cad” in “abracadabra” (h) “apple” in “pineapple” (i) “pine” > “pineapple”
Answer: (a) to (i)
>>> "Wow Python"[1] 'o'
>>> "Strings are fun."[5] 'g'
>>> len("awesome") 7
>>> "Mystery"[:4] 'Myst'
>>> "apple" > "pineapple" False
>>> "pineapple" < "Peach" False
>>> "cad" in "abracadabra" True
>>> "apple" in "pineapple" True
>>> "pine" > "pineapple" False
Q.NO. PAGE NO.
9 Pg.278
Q.NO.10.
Considering the same strings s1 and s2 of question 5 above, evaluate the following expressions:
(a) s1[1:3] (b) s1[2]+s2[:2] (c) s1+s2[-1]
(d) s1[:3]+s2[3:] (e) s1[:-1]+s2[-1:]
Answer:
>>> s1 'spam'
>>> s2 'ni!'
>>> s1[1:3] 'pa'
>>> s1[2]+s2[:2] 'ani'
>>> s1+s2[-1] 'spam!'
>>> s1[:3]+s2[3:] 'spa'
>>> s1[:-1]+s2[-1:] 'spa!'
Check Point 9.2 (Chapter 9) – Pg.284
Q.NO.1.
What is the role of these functions?
(i) isalpha() (ii) isalnum() (iii) isdigit() (iv) isspace()
Answer:
(i) isalpha() – returns True if all the characters in the string are alphabetic and there is atleast one
character, otherwise it returns False.

34
(ii) isalnum() – returns True if all the characters in the string are alphanumeric (alphabets or numbers) and
there is atleast one character, otherwise it returns False.
(iii) isdigit() – returns True if all the characters in the string are digits and there is atleast one character,
otherwise it returns False. Spaces and Special characters are not allowed. Decimal numbers and Complex
numbers are not considered as digits.
(iv) isspace() – returns True if all the characters in the string are whitespaces in the string and there is
atleast one character, otherwise it returns False.
Q.NO.2.
Name the case related string manipulation functions.
Answer:
isupper(), islower(), upper(), lower(), capitalize()
Q.NO.3.
How is islower() function different from lower() function?
Answer: The islower() function returns True if all cased characters in the string are lowercase and there is
atleast one character that is cased, otherwise it returns False. The lower() function converts all the
characters of the string to lower case. Numbers and spaces are allowed, but ignored during the change of
case.
Q.NO.4.
What is the utility of find() function?
Answer: The utility of find() function is to find the substring from the main string. It may take 3 arguments
such as substring or a substring variable, starting index and ending index where the last two arguments are
optional.
Q.NO.5.
How is capitalize() function different from upper() function?
Answer: The capitalize() function converts the 1st character of the string alone to upper case and all the
remaining characters in to lower case. The upper() function converts all the characters of the string to
upper case.

Solved Problems (Chapter 9) – Pg.285


Q.NO. PAGE NO.
1-2 285
3-4 286
5-7 287
8-9 288

35
Type A : Short Answer Questions/Conceptual Questions (Page: 289)
Q.NO.1.
Write a Python script that traverses through an input string and prints its characters in different lines -
two characters per line.
Program Coding:
string=input("Enter a String: ")
for i in range(0,len(string),2):
print(string[i],string[i+1])
Output:
Enter a String: Python
Py
th
on
Q.NO.2.
Out of the following operators, which ones can be used with strings?
=, -, *, /, //, %, >, <>, in, not in, <=
Answer:
=, *, >, in, not in, <=
Q.NO.3.
What is the result of following statement, if the input is ‘Fun’?
print (input (“ … ")+"trial"+"Ooty" *3)
Answer:
>>> print(input("Fun")+"trial"+"Ooty" *3) Fun
Q.NO.4.
Which of the following is not a Python legal string operation?
(a) 'abc’ + 'abc’ (b) 'abc' * 3 (c) 'abc' + 3 (d) 'abc’.lower()
Answer:
The following are not the legal string operations:
(c) 'abc' + 3 - Reason: Two operands should either be strings for + operator to be used for String
concatenation
Q.NO.5.
Can you say strings are character lists? Why? Why not?
Answer: Strings have all the features of character lists and has an additional feature of indexing both
forward (0 to n-1) and backward (-1 to –n), but strings will not be printed as comma separated values like a
typical list.
36
Q.NO.6.
Given a string S="CARPE DIEM". If n is length/2 (length is the length of the given string), then what
would following return?
(a) S[:n] (b) S[n:] (c) S[n:n] (d) (b) S[1:n] (e) S[n:length-1]
Answer: (a) to (e)
>>> S="CARPE DIEM"
>>> n=int(len(S)/2) #Note: It returns a float value, so it is type casted to integer
>>> n 5
>>> S[:n] 'CARPE'
>>> S[n:] ' DIEM'
>>> S[n:n] ''
>>> S[1:n] 'ARPE'
>>> S[n:len(S)-1] ' DIE'
Q.NO.7.
From the string S="CARPE DIEM”, which ranges return "DIE" and "CAR"?
Answer:
>>>S[6:9] "DIE"
>>>S[0:3] "CAR"
Q.NO.8.
What would following expression return?
(a) "Hello World".upper().lower()
(b) "Hello World".lower().upper()
(c) "Hello World".find( "Wor", 1, 6)
(d) "Hello World".find( "Wor")
(e) "Hello World".find( "wor”)
(f) "Hello World".isalpha()
(g) "Hello World".isalnum()
(h) "1234".isdigit()
(i) "123FGH".isdigit()
Answer: (a) to (i)
>>> "Hello World".upper().lower() 'hello world'
>>> "Hello World".lower().upper() 'HELLO WORLD'
>>> "Hello World".find("Wor", 1, 6) -1
# -1 is returned when it is not found, lowest index is returned when it is found
>>> "Hello World".find("Wor") 6
37
>>> "Hello World".find("wor") -1
>>> "Hello World".isalpha() False
>>> "Hello World".isalnum() False
>>> "1234".isdigit() True
>>> "123FGH".isdigit() False
Q.NO.9.
Which functions would you choose to use to remove leading and trailing white spaces from a given
string?
Answer: strip() function #Not included in Textbook
>>> " Hello ".strip() 'Hello'
Note: If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
Q.NO.10.
Try to find out if for any case, the string functions isalnum() and isalpha() return the same result.
Answer: The case when the inputs for both the functions are completely characters
>>> "hello".isalpha() True
>>> "hello".isalnum() True
Note: If the string with space in between are used then both will return False as given below:
>>> "he llo".isalpha() False
>>> "he llo".isalnum() False
Q.NO.11.
Suggest appropriate functions for the following tasks:
(i) To check whether the string contains digits
(ii) To find for the occurrence a string within another string
(iii) To convert the first letter of a string to upper case
(iv) To capitalize all the letters of the string
(v) To check whether all letters of the string are in capital letters
(vi) To remove from right of a string all string-combinations from a given set of letters
(vii) To remove all white spaces from the beginning of a string
Answer:
(i) string.isalnum() (ii) string.find(sub[,start[,end]]) (iii) string.capitalize()
(iv) string.upper() (v) string.isupper() (vi) string.replace()
(vii) string.lstrip()
Examples:
>>> string="abracadabra123"
>>> string.isalnum() True
>>> string.find("ra",2,6) 2

38
>>> string.find("ra",8,11) 9
>>> string.capitalize() 'Abracadabra123'
>>> string.upper() 'ABRACADABRA123'
>>> string.isupper() False
>>> string.replace("a","") 'brcdbr123'
>>> string=" aba 1 "
>>> string.lstrip() 'aba 1 '
Type B : Application Based Question (Page: 290)
Q.NO.1.
What is the result of the following expressions ?
(a) (b) (c) (d)
print(""" text="Test.\nNext line." print('One', 'Two'*2) s='0123456789'
1 print(text) print('One'+'Two'*2) print(s[3],",",s[0:3],"-",s[2:5])
2 print(len('0123456789')) print(s[:3],"-",s[3:],",",s[3:100])
3 print(s[20:],s[2:1],s[1:1])
""")
(e)
s='987654321'
print(s[-1],s[-3])
print(s[-3:],s[:-3])
print(s[-100:-3],s[-100:3])
Answers:
(a) (b) (c) (d) (e)
1 Test. One TwoTwo 3 , 012 - 234 1 3
2 Next line. OneTwoTwo 012 - 3456789 , 3456789 321 987654
3 10 #empty line 987654 987
Q.NO.2.
What will be the output produced by following code fragments?
(a) (b) (c)
y=str(123) x="hello"+\ x="hello world"
x="hello"*3 "to Python"+\ print(x[:2],x[:-2],x[-2:])
print(x,y) "world" print(x[6],x[2:4])
x="hello" + "world" for char in x: print(x[2:-3],x[-4:-2])
y=len(x) y=char
print(y,x) print (y,' :',end=' ')

39
Answers:
(a) (b) (c)
hellohellohello 123 h :e :l :l :o :t :o : he hello wor ld
10 helloworld :P :y :t :h :o :n :w w ll
:o :r :l :d : llo wo or
# in single line
Q.NO.3.
Carefully go through the code given below and answer the questions based on it:
theStr=" This is a test "
inputStr=input(" Enter integer: ")
inputlnt=int(inputStr)
testStr=theStr
while inputlnt>=0:
testStr=testStr[1:-1]
inputlnt=inputlnt-1
testBool=' t ' in testStr
print(theStr) #Line1
print(testStr) #Line2
print(inputlnt) #Line3
print(testBool) #Line4
(i) Given the input integer 3, what output is produced by Line 1?
(a) This is a test (b) This is a (c) is a test (d) is a (e) None of these
(ii) Given the input integer 3, what output is produced by Line 2?
(a) This is a test (b) s is a t (c) is a test (d) is a (e) None of these
(iii) Give the input integer 2, what output is produced by Line 3?
(a) 0 (b) 1 (c) 2 (d) 3 (e) None of these
(iv) Given the input integer 2, what output is produced by Line 4 ?
(a) False (b) True (c) 0 (d) 1 (e) None of these
Output:
(i,ii) (iii,iv)
Enter integer: 3 Enter integer: 2
This is a test This is a test
s is a t is is a te
-1 -1
False False

Answer:
(i) (a) This is a test
(ii) (b) s is a t
(iii) (e) None of these (i.e) -1
(iv) (a) False

40
Q.NO.4.
Carefully go through the code given below and answer the questions based on it:
testStr="abcdefghi"
inputStr=input("Enter integer:")
inputlnt=int(inputStr)
count=2
newStr=' '
while count <=inputlnt:
newStr=newStr+testStr[0:count]
testStr=testStr[2:] #Line1
count=count+ 1
print(newStr) #Line2
print(testStr) #Line3
print(count) #Line4
print(inputlnt) #Line5
(i) Given the input integer 4, what output is produced by Line 2?
(a) abcdefg (b) aabbccddeeffgg (c) abcdeefgh (d) ghi (e) None of these
(ii) Given the input integer 4, what output is produced by Line 3?
(a) abedefg (b) aabbccddeeffgg (c) abcdeefgh (d) ghi (e) None of these
(iii) Given the input integer 3, what output is produced by Line 4?
(a) 0 (b) 1 (c) 2 (d) 3 (e) None of these
(iv) Given the input integer 3, what output is produced by Line 5?
(a) 0 (b) 1 (c) 2 (d) 3 (e) None of these
(v) Which statement is equivalent to the statement found in Line 1?
(a) testStr= testStr[2:0] (b) testStr=testStr[2:-1]
(c) testStr= testStr[2:-2] (d) testStr=testStr-2
(e) None of these
Output:
(i,ii) (iii,iv)
Enter integer:4 Enter integer:3
abcdeefgh abcde
ghi efghi
5 4
4 3

Answer:
(i) (c) abcdeefgh
(ii) (d) ghi
(iii) (e) None of these (i.e) 4
(iv) (d) 3
(v) (e) None of these #Refer below – (To avoid value loss of original string, testStr1 is used additionally)
41
>>> testStr="abcdefghi"
>>> testStr1=testStr[2:] #Line1
>>> print(testStr1)
cdefghi
>>> testStr1=testStr[2:0] #V-a
>>> print(testStr1)
#Empty string
>>> testStr1=testStr[2:-1] #V-b
>>> print(testStr1)
cdefgh
>>> testStr1=testStr[2:-2] #V-c
>>> print(testStr1)
cdefg
>>> testStr1=testStr-2 #V-d
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
testStr1=testStr-2
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Q.NO.5.
Carefully go through the code given below and answer the questions based on it:
inputStr=input("Give me a string:")
biglnt=0
littlelnt=0
otherlnt=0
for ele in inputStr:
if ele >= 'a' and ele<='m': #Line1
littlelnt=littlelnt + 1
elif ele > 'm' and ele <='z':
biglnt=biglnt + 1
else :
otherlnt=otherlnt + 1
print(biglnt) #Line2
print(littlelnt) #Line3
print(otherlnt) #Line4
print(inputStr.isdigit()) #Line5
42
(i) Given the input abcd what output is produced by Line 2 ?
(a) 0 (b) 1 (c) 2 (d) 3 (e) 4
(ii) Given the input Hi Mom what output is produced by Line 3?
(a) 0 (b) 1 (c) 2 (d) 3 (e) None of these
(iii) Given the input Hi Mom what output is produced by Line 4?
(a) 0 (b) 1 (c) 2 (d) 3 (e) None of these
(iv) Given the input 1+2=3 what output is produced by Line 5?
(a) 0 (b) 1 (c) True (d) False (e) None of these
(v) Give the input Hi Mom, what changes result from modifying Line 1 from
if ele >= 'a’ and ele <='m’ to the expression
if ele >= 'a’ and ele < 'm’ ?
(a) No change (b) otherlnt would be larger (c) littlelnt would be larger
(d) bigint would be larger (e) None of these
Output:
(v)
(i) (ii,iii) (iv) (When Line1 is changed as:
if ele >= 'a' and ele<'m':
Give me a string:abcd Give me a string:Hi Mom Give me a string:1+2=3 Give me a string:Hi Mom
0 1 0 1
4 2 0 1
0 3 5 4
False False False False

Answer:
(i) (a) 0
(ii) (c) 2
(iii) (d) 3
(iv) (d) False
(v) (b) otherlnt would be larger (and littlelnt would be smaller)
Q.NO.6.
Carefully go through the code given below and answer the questions based on it:
in1Str=input("Enter string of digits: ")
in2Str=input("Enter string of digits: ")
if len(in1Str)>len(in2Str) :
small=in2Str
43
large=in1Str
else:
small=in1Str
large=in2Str
newStr=' '
for element in small:
result=int(element)+int(large[0])
newStr=newStr+str(result)
large=large[1:]
print(len(newStr)) #Line 1
print(newStr) #Line 2
print(large) #Line 3
print(small) #Line 4
(i) Given a first input of 12345 and a second input of 246, what result is produced by Line 1?
(a) 1 (b) 3 (c) 5 (d) 0 (e) None of these
(ii) Given a first input of 12345 and a second input of 246, what result is produced by Line 2?
(a) 369 (b) 246 (c) 234 (d) 345 (e) None of these
(iii) Given a first input of 123 and a second input of 4567, what result is produced by Line 3?
(a) 3 (b) 7 (c) 12 (d) 45 (e) None of these
(iv) Given a first input of 123 and a second input of 4567, what result is produced by Line 4?
(a) 123 (b) 4567 (c) 7 (d) 3 (e) None of these
Output:
(i,ii) (iii,iv)
Enter string of digits: 12345 Enter string of digits: 123
Enter string of digits: 246 Enter string of digits: 4567
4 4
369 579
45 7
246 123

Answer:
(i) (e) None of these (i.e) 4
(ii) (a) 369
(iii) (b) 7
(iv) (a) 123

44
Q.NO.7.
Find the output if the input string is ‘Test’
(a) (b)
S= input("Enter String: ") S= input("Enter String: ")
RS=" " RS=" "
for ch in S: for ch in S:
RS=ch+RS RS=ch+2+RS
print(S+RS) print(RS+S)
Answer: (Output)
(a) (b)
Enter String: Test Enter String: Test
TesttseT TypeError: must be str, not int

Q.NO.8.
Find the errors. Find the Iine numbers causing errors.
(a) (b) (c) (d)
1. S="PURA VIDA” 1. S="PURA VIDA" 1. S="PURA VIDA” 1. S="PURA VIDA”
2. print(S[9]+ S[9:15]) 2. S1=S[: 10]+ S[10 :] 2. S1=S*2 2. S1=S[: 5]
3. S2=S[10]+ S[-10] 3. S2=S1[-19] + S1[-20] 3. S2=S[5:]
4. S3=S1[-19 :] 4. S3= S1 * S2
5. S4=S2 +’3’
6. S5= S1+ 3
Answer: (Output)
print(S[9]+ S[9:15]) causes
(a) Line 2
IndexError: string index out of range
S2=S[10]+ S[-10] causes
(b) Line3
IndexError: string index out of range
S2=S1[-19]+S1[-20] causes
(c) Line3
IndexError: string index out of range
S3= S1 * S2 causes
TypeError: can't multiply sequence by non-int of type 'str' Line4
(d)
S5= S1+ 3 causes Line6
TypeError: must be str, not int

45
Type C : Programming Practice/Knowledge Based Questions (Chapter 9) (Pg.293)
Q.NO.1.
Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the
area code and the next three numbers. For example, 017-555-1212 is a legal input
Display if the phone number entered is valid format or not and display if the phone number is valid or
not (i.e., contains just the digits and dash at specific places).
Program Coding:
p1=input("Enter the Phone number [10 digits, Hyphens after each 3 digits]: ")
a=p1[0:3]
b=p1[4:7]
c=p1[8:13]
if p1.find('-',3)== 3 and p1.find('-',7)==7 and a.isdigit() == True and b.isdigit() == True and c.isdigit() == True:
print("Phone Number is Valid!")
else:
print("Phone Number is Invalid!")
Output:
Enter the Phone number [10 digits, Hyphens after each 3 digits]: 017-555-1212
Phone Number is Valid!
Enter the Phone number [10 digits, Hyphens after each 3 digits]: 0175-95-1212
Phone Number is Invalid!
Q.NO.2.
Write a program that:
 prompt the user for a string
 extract all the digits from the string
 If there are digits:
 sum the collected digits together
 print out:
 the original string
 the digits
 the sum of the digits
 If there are no digits:
 print the original string and a message "has no digits"
Sample
 given the input: abc123
 prints abc123 has the digits 123 which sum to 6
 given the input abcd
 prints abcd has no digits
Program Coding:
a=input("Enter a String (It can be with digits!): ")

46
sum=0
l=[]
if a.isalpha()==True:
print("The original string: ",a)
print("The string has no digits")
else:
for i in a:
if i.isdigit():
l.append(i)
sum+=int(i)
print("The original string: ",a)
print("The digits: ",l)
print("The sum of the digits: ",sum)
Output:
Enter a String (It can be with digits!): lion123
The original string: lion123
The digits: ['1', '2', '3']
The sum of the digits: 6
Enter a String (It can be with digits!): lionking
The original string: lionking
The string has no digits
Q.NO.3.
Write a program that should prompt the user to type some sentence(s) followed by "enter". It should
then print the original sentence(s) and the following statistics relating to the sentence(s):
 A Number of words
 A Number of characters (including white-space and punctuation)
 A Percentage of characters that are alpha numeric
Hints
 Assume any consecutive sequence of non-blank characters is a word
Program Coding:
a=input("Enter the sentence(s): ")
words=a.split()
sum=0
print("The number of words in string: ",len(words))
print("The number of characters (including white space and punctuation): ",len(a))
for i in a:
if i.isalnum()==True:
sum+=1

47
print("Number of characters that are alphanumeric:", sum)
print("Percentage of characters that are alphanumeric:", round(sum/len(a)*100,2),"%")
Output:
Enter the sentence(s): The 1st runner-up is with the ID:345@sport. Congrats!
The number of words in string: 8
The number of characters (including white space and punctuation): 54
Number of characters that are alphanumeric: 41
Percentage of characters that are alphanumeric: 75.93 %
Q.NO.4.
Write a Python program as per specifications given below:
 Repeatedly prompt for a sentence (string) or for 'q’ to quit
 Upon input of a sentence s, print the string produced from s by converting each lower case letter
to upper case and each upper case letter to lower case
 All other characters are left unchanged
For example,
==================RESTART=====================
Please enter a sentence, or 'q’ to quit: This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q’ to quit: What's up Doc???
wHAT'S UP dOC???
Please enter a sentence, or 'q to quit: q
Program Coding:
while True:
print("Please enter a sentence, or 'q’ to quit: ",end="")
s=input()
if(s!='q'):
print(s.swapcase()) #Not in the Textbook
else:
break
Output:
Please enter a sentence, or 'q’ to quit: This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q’ to quit: What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q’ to quit: q
48
Q.NO.5.
Write a program that does the following:
 takes two inputs: the first, an integer and the second, a string
 from the input string extract all the digits, in the order they occurred, from the string
 if no digits occur, set the extracted digits to 0
 add the integer input and the digits extracted from the string together as integers
 print a string of the form:
“integer_ input + string_digits=sum”
For example:
For inputs 12, ‘abc123’  ‘12 + 123 = 135’
For inputs 20, ‘a5b6c7’  ‘20 + 567 = 587’
For inputs 100, ‘hi mom’  ‘100 + 0 = 100’
Program Coding:
inp1=int(input("Enter an integer: "))
inp2=input("Enter a string: ")
l=""
sum=num=0
for i in inp2:
if i.isdigit()==True:
l+=i
else:
l=0
print(inp1,'+',int(l),'=',inp1+int(l))
Output:
Enter an integer: 12 Enter an integer: 20 Enter an integer: 100
Enter a string: abc123 Enter a string: a5b6c7 Enter a string: hi mom
12 + 123 = 135 20 + 567 = 587 100 + 0 = 100
Q.NO.6.
On what principles does Python compare two strings? Write a program that takes two strings from the
user and displays the smaller string in single line and the larger string as per this format:
1st letter last letter
2nd letter 2nd last letter
3rd Letter 3rd last letter
:
For example,
if the two strings entered are Python and PANDA then the output of the program should be:

49
PANDA
P n
y o
t h
Answer:
Python compares two strings on the basis of character by character comparison rules for Unicode
(i.e. dictionary order). Internally Python compares using Unicode values (called ordinal value) and for the
most common characters, the ASCII values and Unicode values are the same.
Program Coding:
str1=input("Enter String1: ")
str2=input("Enter String2: ")
if str1<str2:
print(str1)
n=len(str2)
for i in range(n//2):
j=i+1
print(" "*i,str2[i]," "*(n-2*j)+str2[-j])
if n%2==1:
print((n//2)*' ' + str2[n//2]) #If the length is odd - To print the middle character
else:
print("Retry by Swapping the input strings!")
Output:
Enter String1: PANDA Enter String1: python
Enter String2: python Enter String2: PANDA
PANDA Retry by Swapping the input strings!
p n
y o
th
Q.NO.7.
Write a program to convert a given number into equivalent Roman number (store its value as a string).
You can use following guidelines to develop solution for it:
 From the given number, pick successive digits, using %10 and /10 to gather the digits from right to
left

50
 The rules for Roman Numerals involve using four pairs of symbols for ones and five, tens and
fifties, hundreds and five hundreds. An additional symbol for thousands covers all the relevant
bases
 When a number is followed by the same or smaller number, it means addition. “II” is two 1’s= 2.
“VI” is 5+1=6.
 When one number is followed by a larger number, it means subtraction. "IX is 1 before 10=9.
“IIX” isn’t allowed, this would be "VIII”. For numbers from 1 to 9, the symbols are “I" and "V”, and
the coding works like this. “I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”
 The same rules work for numbers from 10 to 90, using “X” and “L”. For numbers from 100 to 900,
using the symbols “C” and “D”. For numbers between 1000 and 4000, using "M”.
Here are some examples. 1994=MCMXCIV, 1956- MCMLVI, 3888-MMMDCCCLXXXVIII
Program Coding:
#With even more simpler logic than mentioned in text book
#To better understand the logic, work each statement in interactive mode
n=int(input("Enter a number: "))
m=n
val=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
sym=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
rom=""
while n>0:
for i in range(len(val)):
rom+=(n//val[i])*sym[i]
n=n%val[i]
print("The Roman equivalent of",m,"is",rom)
Output:
Enter a number: 1994 Enter a number: 1956 Enter a number: 3888
The Roman equivalent of 1994 is The Roman equivalent of 1956 is The Roman equivalent of 3888 is
MCMXCIV MCMLVI MMMDCCCLXXXVIII

51
CHAPTER – 10 (Debugging Programs)
Check Point 10.1 (Chapter 10) – Pg.306
Q.NO.1.
What is debugger?
Answer: Debugger works in order to remove the bugs from the program, by rectifying the code by
incorporating the debugging techniques. The commonly used Python debugger is pdb.
Q.NO.2.
What is the role of debugger?
Answer: Debugger is meant for doing the debugging process of locating the place of error, cause of error,
cause of error, and correcting the code accordingly.
Q.NO.3.
Differentiate between an error and exception.
Answer:
Error Exception
This is a bug in the code that causes irregular output This is an irregular situation that occur during
or stops a program from executing execution/ runtime, which the user have no control
on
Types of Errors: Types of Exceptions:
Compile time error (Syntax & Semantics error), Run EOFError, IOError, NameError, IndexError,
time error, Logical error ImportError, TypeError, ValueError, ZeroDivisionError,
OverflowError,KeyError
Q.NO.4.
Which is easier to fix – an error or exception?
Answer: Fixing the errors is easier, since they are bugs in the code.
Q.NO.5.
Which clauses let you handle exceptions in Python?
Answer: try and except clauses
The format is as follows:
try:
#write here the code that may generate an exception
except:
#write code here about what to do when the exception has occurred
Solved Problems (Chapter 10) – Pg.309
Q.NO. PAGE NO.
1-3 309
4-5 310

52
Assignment (Chapter 10) (Pg.310)
Q.NO.1.
What are main error types ? Which types are most dangerous and why?
Answer: The main error types are Compile time error (Syntax & Semantics error), Run time error, Logical
error. Runtime error can result ranging from terminating a program to system crash. Logical errors are
considered to be the subcategory of Runtime errors. So, runtime error is the most dangerous type of error.
Q.NO.2.
Correct any false statements:
(a) Compile-time errors are usually easier to detect and to correct than run-time errors
(b) Logically errors can usually be detected by the compiler
Answer: (a) True (b) False – Logical errors cannot usually be detected by the compiler
Q.NO.3.
Differentiate between a syntax error and a semantics error.
Answer:
Syntax Error Semantic Error
Syntax refers to formal rules governing the Semantics refers to the set of rules which give the
construction of valid statements in a language. meaning of a statement.
Syntax error occurs when rules of a programming Semantic error occurs when statements are not
language are misused (i.e) when a grammatical rule meaningful
of Python is violated.
Example: Example:
If (a=b): a+2=b
print(“a is equal to b”)
Q.NO.4.
Differentiate between a syntax error and a logical error in a program. When is each type of error likely
to be found?
Answer:
Syntax Error Logical Error
Syntax refers to formal rules governing the Logic refers to the fundamental construct which give
construction of valid statements in a language. the correct expected result for a program
Syntax error occurs when rules of a programming Logical error occurs when the algorithm is not
language are misused (i.e) when a grammatical rule implemented correctly or due to the mistaken
of Python is violated. analysis of the problem
These errors can be found when the programming These errors can be found when the program’s
construct is well understood objective is well understood
Example: Example:
If (a=b): z = x+y/2
print(“a is equal to b”) (if it is intended to produce the average of x and y

53
Q.NO.5.
What is the difference between an error and exception?
Answer:
Error Exception
This is a bug in the code that causes irregular output This is an irregular situation that occur during
or stops a program from executing execution/ runtime, which the user have no control
on
Types: Types:
Compile time error (Syntax & Semantics error), Run EOFError, IOError, NameError, IndexError,
time error, Logical error ImportError, TypeError, ValueError, ZeroDivisionError,
OverflowError,KeyError
Q.NO.6.
How can you handle an exception in Python ? Write sample code to illustrate it.
Answer: Exception handling in Python involves the use of try and except clauses, wherein the code that
may generate an exception is written in the try block and the code for handling exception is written in
except block.
Sample Code:
try:
print(“The result of 100/2=”,100/2)
print(“The result of 100/0=”,100/0)
except:
print(“Division by Zero! Denominator cannot be Zero!”)
Q.NO.7.
Name some common built-in exceptions in Python.
Answer: Types of Exceptions are as follows: EOFError, IOError, NameError, IndexError, ImportError,
TypeError, ValueError, ZeroDivisionError, OverflowError,KeyError
Q.NO.8.
When does these exceptions occur?
(a) Type Error (b) Index Error (c) Name Error
Answer:
(a) Type Error Occur when the an operation or function is applied to an object of an inappropriate
type. e.g.if you try to compute a square root of a string value
(b) Index Error Raised when a sequence subscript or index is out of range. e.g. from a string of length 4
if you try to read a value of index like 4 or more i.e., string[4], string[5] etc., will raise
exception as legal indices for a string of length 4 are 0, 1, 2, 3 and -1, -2, -3, -4 only
(c) Name Error Raised when an identifier name is not found

54
Q.NO.9.
What is debugging and code tracing ?
Answer:
Debugging is a process of locating the place of error, cause of error, cause of error, and correcting the code
accordingly. It figures out the origin of the error, fixing it, review and returns the code to ensure that error
is fixed.
Code Tracing means executing code one line at a time and watching its impact on variables. It is often done
with built-in debugging tools or debuggers.
Q.NO.10.
What are these pdb commands used for?
(a) b (b) cl (c) l (d) h (e) n (f) P
Answer:
(a) b List current breakpoints
(b) cl Clear all breakpoints
(c) l Print nearby code
(d) h Help
(e) n Next
(f) P Print variable value

55

You might also like