Worksheet Getting Started With Python Flow of Control and Strings
Worksheet Getting Started With Python Flow of Control and Strings
Ans. ‘Else’ is used along with ‘if’ to define the alternative path if the condition mentioned in the
‘if’ statement is incorrect. This means that only one statement can be evaluated using
if..else statement.
If more than one statement needs to be evaluated, ‘elif’ construct is used. There is no limit
on the number of ‘elif’ construct which should be used in a statement. However, the
conditions mentioned in each ‘elif’ construct should be mutually exclusive i.e. if one of the
conditions in if..elif is correct it should imply that all the other conditions are false.
Ans. The range() function is a built-in function of Python. It is used to create a list containing a
sequence of integers from the given start value to stop value (excluding stop value). This is
often used in for loop for generating the sequence of numbers.
Examples:
Program Output:
Page 1 of 42
iteration. If the loop’s condition is still
true, the loop is entered again, else the
control is transferred to the statement
immediately following the loop.
Example:
Ans. The statement within the body of a loop must ensure that the test condition for the loop
eventually becomes false, otherwise, the loop will run infinitely. Hence, the loop which
doesn’t end is called an infinite loop. This leads to a logical error in the program.
The above statement will create an infinite loop as the value of ‘num’ initially is 20 and each
subsequent loop is increasing the value of num by 1, thus making the test condition num >
10 always true.
5 Write a program to find the grade of a student when grades are allocated as given in the
table below. Percentage of the marks obtained by the student is input to the program.
Page 2 of 42
Ans.
Ans.
Page 3 of 42
Ans.
Ans.
Ans.
Page 4 of 42
Ans.
Ans.
Programming Exercises
1 Write a program that takes the name and age of the user as input and displays a
message whether the user is eligible to apply for a driving license or not. (the eligible
age is 18 years).
Page 5 of 42
Ans.
2 Write a function to print the table of a given number. The number has to be entered by the
user.
Ans.
3 Write a program that prints the minimum and maximum of five numbers entered by
the user.
Ans.
4 Write a program to check if the year entered by the user is a leap year or not.
Page 6 of 42
Ans.
5 Write a program to generate the sequence: –5, 10,–15, 20, –25..... upto n, where n is an
integer input by the user.
Ans. Solution: The given sequence is: –5, 10, –15, 20, –20 The numbers in the sequence are
multiples of 5 and each number at the odd place is negative, while the number at even
place is positive. The series can be generated by checking each index for odd-even and if it
is odd, it will be multiplied by '-1'.
OR
Page 7 of 42
Ans.
7 Write a program to find the sum of digits of an integer number, input by the user.
Do Not use string or string functions
Ans.
8 Write a function that checks whether an input number is a palindrome or not. [Note: A
number or a string is called palindrome if it appears same when written in reverse
order also. For example, 12321 is a palindrome while 123421 is not a palindrome]
Do Not use string or string functions
Ans.
9 Input CP, SP and calculate profit, % profit or loss, % loss or no profit no loss.
10 Write a program to print the first n even natural numbers using for loop.
11 Write a program to print the first n even natural numbers using while loop.
12 Write a program to print the first n odd natural numbers using for loop.
Page 9 of 42
# Write a program to print the first n odd natural numbers using while loop.
n=int(input("Enter a number: "))
print("Displaying first ", n, " odd Natural Numbers using while loop ")
i=1
while i<=2*n:
print(i,end=' ')
i=i+2
print()
Write a Python program to input a, b and c for a quadratic equation and find
and print the roots and nature of roots with appropriate messages.
if D > 0:
print("The equation has two distinct real roots.")
root1 = (-b + (D)**0.5) / (2 * a)
root2 = (-b - (D)**0.5) / (2 * a)
print("Root 1 =", root1)
print("Root 2 =", root2)
elif D == 0:
print("The equation has two equal real roots.")
root1 = -b / (2 * a)
root2 = -b / (2 * a)
print("Root 1 =", root1)
print("Root 2 =", root2)
else:
print("The equation has two complex roots.")
Page 10 of 42
WAP to input 3 numbers, check if they form a triangle.
If they form a triangle, display the type of triangle: (i) Equilateral, (ii) Scalene, (iii)
Isosceles or right triangle. Also find semi perimeter and area of the triangle.
Else display the message, It is not a triangle.
Page 11 of 42
# Sum of the series No. 1 : 1+x+x**2+x**3+.....+x**n
Page 12 of 42
x = float(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
total = 0
for i in range(1, n + 1):
fact=1
for i in range(1,i+1,1):
fact=fact*i
term = (x ** i) / fact
total += term
print("The sum of the series is: ", total)
1. Write a Python program using for loops to print the following pattern:
*
**
***
****
*****
rows = 5
for i in range(1, rows + 1):
print('*' * i)
print()
2. Write a Python program using for loops to print the following pattern:
12345
1234
123
12
1
rows = 5
Page 13 of 42
# Loop from 5 down to 1
for i in range(rows, 0, -1):
for j in range(1, i + 1):
print(j, end='')
print()
print()
3.Write a Python program using for loops to print the following pattern:
A
AB
ABC
ABCD
ABCDE
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print(chr(65 + j), end='')
print()
# Check Perfect Number (A perfect number is a positive integer that is equal to the
sum of its proper divisors, excluding itself. The number 28 is a perfect number.
• Its divisors (excluding itself):
→ 1, 2, 4, 7, 14
• Sum of those divisors:
→ 1 + 2 + 4 + 7 + 14 = 28
So, 28 is a perfect number.
num = int(input("Enter a number: "))
sum_divisors = 0
for i in range(1, num):
if num % i == 0:
sum_divisors += i
if sum_divisors == num:
print("The number is a Perfect number.")
else:
print("The number is not a Perfect number.")
Page 14 of 42
# Check Armstrong Number: An Armstrong number (also known as a narcissistic
number, pluperfect number, or pluperfect digital invariant) is a number that is equal to
the sum of its own digits each raised to the power of the number of digits.
Example (3-digit number): 153
• Number of digits = 3
• Calculate:
13+53+33=1+125+27=1531^3 + 5^3 + 3^3 = 1 + 125 + 27 =
15313+53+33=1+125+27=153
• ✅ Since the result equals the original number, 153 is an Armstrong number
Page 15 of 42
# Check Palindrome: A palindrome number is a number that reads the same forwards
and backwards.
✅ Examples:
• 121 → reversed is 121 ✅
• 1331 → reversed is 1331 ✅
• 7 → reversed is 7 ✅
• num = int(input("Enter a number: "))
n = num
reversed_num = 0
while n > 0:
digit = n % 10
reversed_num = reversed_num * 10 + digit
n //= 10
if reversed_num == num:
print("The number is a Palindrome.")
else:
print("The number is not a Palindrome.")
● Write a program to input a number and check if the number is a prime or composite
number.
Page 16 of 42
● Display the terms of a Fibonacci series.
# Print N terms of Fibonacci series:
# Enter how many terms: 10
# 0 1 1 2 3 5 8 13 21 34
Page 17 of 42
● Write a program to input two numbers and compute the Greatest Common
Divisor (GCD) and Least Common Multiple (LCM) of two integers.
gcd = a
print("GCD is:", gcd)
Write a program to print the following pattern using nested for loops.
If the number entered is 5 then output will be:
1
121
12321
1234321
123454321
Page 18 of 42
Write a program to print the following pattern using nested for loops.
If the number entered is 5 then output will be:
1
121
12321
1234321
123454321
1234321
12321
121
1
Q1
Assertion (A): The if statement in Python can be used without an else or elif.
Reason (R): The else and elif clauses are mandatory in an if statement.
Answer:
• A is True, R is False
• Explanation: The if statement can be used alone. else and elif are optional.
Page 19 of 42
Q2
Assertion (A): The while loop continues until the condition becomes false.
Reason (R): while is used when the number of iterations is not known in advance.
Answer:
• A is True, R is True, and R is the correct explanation of A.
Q3
Assertion (A): The break statement can be used to exit from both for and while loops.
Reason (R): The break statement skips the current iteration and continues with the
next one.
Answer:
• A is True, R is False
• Explanation: break exits the entire loop, while continue skips the current
iteration.
Q4
Assertion (A): The range(5) generates numbers from 0 to 5.
Reason (R): The range() function includes the stop value.
Answer:
• A is False, R is False
• Explanation: range(5) generates values from 0 to 4, excluding the stop value.
Q5
Assertion (A): An else block can be used with both if and while loops in Python.
Reason (R): In Python, else after a loop executes if the loop completes without a
break.
Answer:
• A is True, R is True, and R is the correct explanation of A.
Q6
Assertion (A): The continue statement terminates the loop immediately.
Reason (R): continue skips the rest of the current loop iteration and jumps to the next
one.
Answer:
• A is False, R is True
• Explanation: continue doesn't terminate the loop; it skips to the next iteration.
Q7
Assertion (A): if-elif-else ladder is used when multiple conditions need to be checked.
Reason (R): Only the first true condition in the ladder is executed.
Answer:
• A is True, R is True, and R is the correct explanation of A.
Page 20 of 42
Q8
Assertion (A): Python does not support the switch statement.
Reason (R): Python uses if-elif-else as an alternative to switch.
Answer:
• A is True, R is True, and R is the correct explanation of A.
Q9
Assertion (A): A while loop always executes at least once.
Reason (R): In Python, the condition of the while loop is checked after executing the
loop body.
Answer:
• A is False, R is False
• Explanation: A while loop may not execute at all if the condition is false initially.
Q10
Assertion (A): Indentation is crucial in Python’s flow control structures.
Reason (R): Indentation defines the block of code to be executed under each
condition.
Answer:
• A is True, R is True, and R is the correct explanation of A.
MCQ
x=5
if x > 3:
print("A")
else:
print("B")
A. A
B. B
C. Error
D. Nothing
Answer: A. A
Page 21 of 42
Q3. Which loop is best suited when the number of iterations is unknown?
A. for loop
B. do-while loop
C. while loop
D. loop
Answer: C. while loop
for i in range(3):
if i == 1:
break
print(i)
A. 0 1 2
B. 1 2
C. 0
D. 0 1
Answer: C. 0
i=1
while i < 5:
print(i)
i += 1
A. 4
B. 5
Page 22 of 42
C. Infinite
D. 3
Answer: A. 4
Q9. Which of the following is the correct syntax for a for loop?
A. for (i = 0; i < 10; i++)
B. for i in range(10):
C. for i < 10:
D. for i = 1 to 10:
Answer: B. for i in range(10):
● Write a Python program to input a string or sentence and Count and display
the number of vowels, consonants, uppercase, lowercase characters in string.
Input a string
text = input("Enter a string or sentence: ")
# Initialize counters
vowels = 0
Page 23 of 42
consonants = 0
uppercase = 0
lowercase = 0
vowel_set = 'aeiouAEIOU'
for ch in text:
if ch.isalpha(): # Check if character is a letter
if ch in vowel_set:
vowels += 1
else:
consonants += 1
if ch.isupper():
uppercase += 1
elif ch.islower():
lowercase += 1
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
print("Number of uppercase letters:", uppercase)
print("Number of lowercase letters:", lowercase)
if s == rev:
print(s, 'is Palindrome!')
else:
print(s, 'is not Palindrome!')
Page 24 of 42
#3rd Method for Palindrome
print("3rd Method")
s=input("Enter a string:")
Pali=True
for i in range(len(s)//2):
if s[i]!=s[len(s)-i-1]:
Pali=False
if Pali:
print(s, 'is Palindrome!')
else:
print(s, 'is not Palindrome!')
Page 25 of 42
result += chr(code - 32)
# If uppercase (A-Z), convert to lowercase by adding 32
elif 65 <= code <= 90:
result += chr(code + 32)
else:
result += ch or ch
Ans. (C) 20
2 Which of the following is the correct identifier?
Ans. (A) is
5 Write one example of each of the following in Python:
Page 26 of 42
(i) Syntax Error
(ii) Implicit Type Conversion
Ans. (i) Some of the most common causes of syntax errors in Python are:
Missing quotes.
For example,
print(Hello) instead of print("Hello").
Misspelled reserved keywords
(ii) Implicit type conversion happens when Python automatically
converts one data type to another,
For example:
print(int(24.8))
will convert the float 24.8 to an integer 24.
6 State True or False: The Python interpreter handles logical errors during code
execution.
Ans. False
7 Which of the following expressions evaluates to False?
(A) not(True) and False
(B) True or False
(C) not(False and True)
(D) True and not(False)
Ans. (A) not (True) and False
8 How is a mutable object different from an immutable object in Python?
Identify one mutable object and one immutable object from the following:
(1,2), [1,2], {1:1,2:2}, ‘123’
Page 27 of 42
12 Identify the valid Python identifier from the following:
(A) 2user (B) user@2
(C) user_2 (D) user 2
Ans. (C) user_2
13 What will be the output of the following statement:
print (16*5/4*2/5—8)
(a) -3.33 (b) 6.0
(c) 0.0 (d) -13.33
Ans. (c) 0.0
14 Identify the statement from the following which will raise an error:
(a) print ("A" *3) (b) print (5*3)
(c) print ("15" + 3) (d) print ("15" + "13")
Ans.: (c) print ("15" + 3)
15 What will be the output of the following statement:
print(3-2**2**3+99/11)
a. 244 b. 244.0
c. -244.0 d. Error
Ans. c. -244.0
16 State True or False. “Comments are not executed by interpreter.”
Ans.: True
17 Which of the following is not a sequential datatype in Python?
(a) Dictionary (b) String (c) List (d) Tuple
Ans.: (a) Dictionary
18 Consider the given expression:
7<4 or 6>3 and not 10==10 or 17>4
Which of the following will be the correct output if the given expression is
evaluated?
(a) True (b) False (c) NONE (d) NULL
Ans.: (a) True
19 Which of the following is an example of identity operators of Python?
(a) is (b) on (c) in (d) not in
Ans.: (a) is
20 What will the following expression be evaluated to in Python?
print(6/3 + 4**3//8-4)
(a) 6.5 (b) 4.0 (c) 6.0 (d) 4
Ans (c) 6.0
21 State True or False. “Identifiers are names used to identify a variable, function
in a program”.
Ans True
22 Which of the following is a valid keyword in Python?
(a) false (b) return (c) non_local (d) none
Page 28 of 42
Ans (b) return
23 Consider the given expression:
5<10 and 12>7 or not 7>4
Which of the following will be the correct output, if the given expression is
evaluated ?
(a) True (b) False (c) NONE (d) NULL
Ans (a) True
24 Which of the following operators will return either True or False?
(a) += (b) != (c) = (d) *=
Ans (b) !=
25 What will the following expression be evaluated to in Python?
print(4+3*5/3–5%2)
(a) 8.5 (b) 8.0 (c) 10.2 (d) 10.0
Ans (b) 8.0
26 State True or False – “Variable declaration is implicit in Python.”
Ans.:
TRUE
27 Which of the following is an invalid datatype in Python?
(a) Set (b) None (c)Integer (d)Real
Ans: (d) Real
28 Consider the given expression:
not True and False or True
Which of the following will be correct output if the given expression is
evaluated?
(a) True
(b) False
(c) NONE
(d) NULL
Ans: (a) True
29 What will the following expression be evaluated to in Python?
print(15.0 / 4 + (8 + 3.0))
Page 29 of 42
a. list
b. tuple
c. dictionary
d. set
Ans.: d. set
32 Which of these Python data structures would be most suited to store the list
of Indian states and their corresponding capitals?
a. list
b. tuple
c. dictionary
d. set
Ans.: c. dictionary
Ans.: c. p = p - 5
Ans.: b. 1.0
Page 30 of 42
section = "A"
students = 30
print ("There are", students, "students in class", class, section)
However, when she ran the program, she got the following output:
File ".\print_students.py", line 1
class = 5
^
SyntaxError: invalid syntax
Which of these changes will make the program run without error?
Which of these changes will make the program run without error?
a. writing '==' instead of '=' (correct assignment operator)
b. writing "5" instead of 5 (variable should be a string)
c. changing the variable name ('class' is a reserved word)
d. adding a colon (':') at the end of the statement (begin indented block)
Page 31 of 42
Ans.: c. This is Delhi. # Delhi is the capital of India.
Page 32 of 42
b. integer
c. list
d. tuple
Ans.: a. string
46 Which of the following symbol is used in Python for single line comment?
a. /
b. /*
c. //
d. #
Ans.: d. #
47 Evaluate the following expression and identify the correct answer.
16 - (4 + 2) * 5 + 2**3 * 4
a. 54
b. 46
c. 18
d. 32
Ans.: c. 18
Page 33 of 42
(D) not
Ans.: (B) <
51 Which of the following is/are immutable object types in Python ?
(A) List
(B) String
(C) Tuple
(D) Dictionary
Ans.:
(B) String (C) Tuple
52 Evaluate the following Python expression:
2 * 3 + 4 ** 2 - 5 // 2
Ans.: 20
53 Evaluate the following Python expression:
6<12 and not (20 > 15) or (10 > 5)
Ans.: True
54 Find the invalid identifier from the following:
a) MyName b) True c) 2ndName d) My_Name
Ans.: b) True c) 2ndName
55 Identify the valid arithmetic operator in Python from the following.
a) ? b) < c) ** d) and
Ans.: c) **
56 (i) Evaluate the following expressions:
6 * 3 + 4**2 // 5 - 8
Ans.: 13
(ii) Evaluate the following expressions:
10 > 5 and 7 > 12 or not 18 > 3
Ans.: False
57 (a) Which of the following is not a valid variable name in Python. Justify reason
for it not being a valid name:
(i) 5Radius (ii)Radius_ (iii) _Radius (iv) Radius
Ans.: (i) 5Radius
Page 34 of 42
(i) // (ii) ? (iii) < (iv) and
Ans.: (i) //
(b) Write the type of tokens from the following:
(i) if (ii) roll_no
Ans,:( i) Key word (ii) Identifier
60 (d) Rewrite the following code in python after removing all syntax error(s).
Underline each correction done in the code.
input('Enter a word',W)
if W = 'Hello'
print('Ok')
else:
print('Not Ok')
61 (a) Write the names of any four data types available in Python.
Ans. Numbers
Integer
Boolean
Floating Point
Complex
None
Sequences
Strings
Tuple
List
Sets
Mappings
Dictionary
( ½ mark each for writing correct data types- Any four datatypes)
Page 35 of 42
(A) 0 (B) 6
(C) -1 (D) ValueError
Page 36 of 42
n = len(s)
m=""
for i in range (0, n) :
if (s[i] >= 'a' and s[i] <= 'm') :
m = m + s [i].upper()
elif (s[i] >= 'o' and s[i] <= 'z') :
m = m +s [i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '@'
print (m)
69 Consider the statements given below and then choose the correct output from the
given options:
myStr="MISSISSIPPI"
print (myStr[:4] +" # "+myStr[-5:] )
event="G20 Presidency@2023"
L=event.split(' ')
print(L[::-2])
Page 37 of 42
Mark the correct choice as
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
18. Assertion (A): The expression "HELLO".sort() in Python will give an error.
Reason (R): sort() does not exist as a method/function for strings in Python.
Ans: (a) Both (A) and (R) are true and (R) is
the correct explanation for (A).
72 (A) Write the Python statement for each of the following tasks using built-in
functions/methods only:
(ii) To display the number of occurrences of the substring "is" in a string named
message.
For example if the string message contains "This is his book”, then the output will
be 3.
Ans.:
message ="This is his book"
print(message.count('is'))
Output:
3
Page 38 of 42
Ans.: Output:
R*A*C*E*C*A*R*
C#a#r#
R*A*D*A*R*
74 Select the correct output of the code:
s="Python is fun"
l=s.split()
s_new="-".join([l[0].upper(),l[1],l[2].capitalize()])
print(s_new)
Options:
a. PYTHON-IS-Fun
b. PYTHON-is-Fun
c. Python-is-fun
d. PYTHON-Is -Fun
Ans. b. PYTHON-is-Fun
75 Consider the statements given below and then choose the correct output from the
given options:
pride="#G20 Presidency"
print(pride[-2:2:-2])
Options:
a. ndsr
b. ceieP0
c. ceieP
d. yndsr
Ans. Option b
ceieP0
76 Write a function, lenWords(STRING), that takes a string as an argument and
returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the
tuple will have (4, 3, 2, 4, 4, 3)
Ans. STRING = "Come let us have some fun"
def lenWords(STRING):
T=()
L=STRING.split()
for word in L:
length=len(word)
Page 39 of 42
T=T+(length,)
return T
print(lenWords(STRING))
Text1="IND-23"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>"0" and Text1[I]<="9":
Val=int(Text1[I])
Val = Val+1
Text2=Text2+str(Val)
elif Text1[I]>="A" and Text1[I]<="Z":
Text2=Text2+(Text1[I+1])
else:
Text2=Text2+"*"
I+=1
print(Text2)
Ans. ND-*34
78 Select the correct output of the code:
S="Amrit Mahotsav @ 75"
A=S.split(" ",2)
print(A)
(a) ('Amrit', 'Mahotsav','@','75') (b) ['Amrit','Mahotsav','@ 75']
(c) ('Amrit', 'Mahotsav','@75') (d) ['Amrit','Mahotsav','@','75']
Ans.:(b) ['Amrit', 'Mahotsav', '@ 75']
79 Which of the following statement(s) would give an error after executing the
following code?
S="Happy" # Statement 1
print(S*2) # Statement 2
S+="Independence" # Statement 3
S.append("Day") # Statement 4
print(S) # Statement 5
(a) Statement 2 (b) Statement 3
(c) Statement 4 (d) Statement 3 and 4
Ans.: c) Statement 4
80 (a) Given is a Python string declaration : NAME = "Learning Python is Fun" Write the
output of : print(NAME[-5:-10:-1])
Ans.: si no
81 Select the correct output of the code :
Page 40 of 42
S= "Amrit Mahotsav @ 75"
A=S.partition (" ")
print (a)
(a) ('Amrit Mahotsav','@','75')
(b) ['Amrit','Mahotsav','@','75']
(c) ('Amrit', 'Mahotsav @ 75')
(d) ('Amrit','' , 'Mahotsav @ 75')
Ans (d) ('Amrit', '', 'Mahotsav @ 75')
82 Select the correct output of the code:
a = "Year 2022 at All the best"
a = a.split('2')
b = a[0] + ". " + a[1] + ". " + a[3]
print (b)
(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5
Page 41 of 42
s="welcome2cs"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'&'
print(m)
Ans. sELCcME&Cc
86 (d) Find and write the output of the following python code: 2
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print (Msg3)
Ans. G*L*TME
Page 42 of 42