0% found this document useful (0 votes)
4 views

Worksheet Getting Started With Python Flow of Control and Strings

Uploaded by

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

Worksheet Getting Started With Python Flow of Control and Strings

Uploaded by

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

Worksheet Getting started with Python, Flow of Control and Strings

1 What is the difference between else and elif construct of if statement?

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.

2 What is the purpose of range() function? Give one example.

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:

3 Differentiate between break and continue statements using examples.

Ans. Break Continue


The 'break' statement alters the normal When a 'continue' statement is
flow of execution as it terminates the encountered, the control skips the
current loop and resumes execution of execution of remaining statements
the statement following that loop. inside the body of the loop for the
current iteration and jumps to the
beginning of the loop for the next

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:

4. What is an infinite loop? Give one 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.

6 Find the output of the following program segments:

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.

Ans. Cp= int(input("Enter Cost Price"))


Sp= int(input("Enter Selling Price"))
Page 8 of 42
if Sp>Cp:
Profit= Sp-Cp
pp= (Profit/Cp)*100
print("Profit is ", Profit)
print("Profit percent is ", pp)
elif Cp>Sp:
Loss= Cp-Sp
pl= Loss/Cp*100
print("Loss is ", Loss)
print("Loss percent is ", pl)
else:
print("Neither profit nor loss")

10 Write a program to print the first n even natural numbers using for loop.

Ans. n=int(input("Enter a number: "))


print("Displaying first ", n, " even Natural Numbers using for loop: ")
for i in range(2,2*n+1,2):
print(i,end=' ')
print()

11 Write a program to print the first n even natural numbers using while loop.

n=int(input("Enter a number: "))


print("Displaying first ", n, " even Natural Numbers using while loop ")
i=2
while i<=2*n:
print(i,end=' ')
i=i+2
print()

12 Write a program to print the first n odd natural numbers using for loop.

Ans. n=int(input("Enter a number: "))


print("Displaying first ", n, " odd Natural Numbers using for loop: ")
for i in range(1,2*n,2):
print(i,end=' ')
print()

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.

a = float(input("Enter coefficient a: "))


b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

print("\nQuadratic Equation: ",a,'*x²+', b,'*x+',c)


D = b**2 - 4*a*c

print("Discriminant (D) = ", D)

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.

a = float(input("Enter side 1: "))


b = float(input("Enter side 2: "))
c = float(input("Enter side 3: "))

if (a + b > c) and (a + c >b) and (b + c > a):


print("It is a triangle.")
if a == b == c:
print("Type: Equilateral triangle")
elif a == b or b == c or a == c:
print("Type: Isosceles triangle")
elif round(a**2 + b**2, 2) == round(c**2, 2) or \
round(a**2 + c**2, 2) == round(b**2, 2) or \
round(b**2 + c**2, 2) == round(a**2, 2):
print("Type: Right triangle")
else:
print("Type: Scalene triangle")
s = (a + b + c) / 2
print("Semi-perimeter: ",s)
# Calculate area using Heron's formula
area = (s * (s - a) * (s - b) * (s - c))**0.5
print("Area of the triangle: ",area)
else:
print("It is not a triangle.")

Page 11 of 42
# Sum of the series No. 1 : 1+x+x**2+x**3+.....+x**n

x = float(input("Enter the value of x: "))


n = int(input("Enter the value of n: "))
total = 0
for i in range(n + 1):
total += x ** i
print("The sum of the series is: ",total)

# Sum of the series No. 2 : 1-x+x**2-x**3+.....+(-1)**n*x**n

x = float(input("Enter the value of x: "))


n = int(input("Enter the value of n: "))
total = 0
for i in range(n + 1):
term = ((-1) ** i) * (x ** i)
total += term
print("The sum of the series is: ",total)

# Sum of the series No. 3 : 1-x+x**2-x**3+.....+(-1)**n*x**nx+x**2/2+x**3/3+ ...+x**n/n

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):
term = (x ** i) / i
total += term
print("The sum of the series is: ",total)
# Sum of the series No. 4 : x+x**2/2!+x**3/3!+ ...+x**n/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()

● Write a program to input a number and determine whether it is a perfect number, an


Armstrong number or a palindrome.

# 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

Example (4-digit number): 9474


• Number of digits = 4
• Calculate:
94+44+74+44=6561+256+2401+256=94749^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 +
2401 + 256 = 947494+44+74+44=6561+256+2401+256=9474
• ✅ 9474 is an Armstrong number

num = int(input("Enter a number: "))


original = num
n = num
digits = 0
while n > 0:
digits += 1
n //= 10
n = num
sum_armstrong = 0
while n > 0:
digit = n % 10
power = 1
for _ in range(digits):
power *= digit
sum_armstrong += power
n //= 10
if sum_armstrong == original:
print("The number is an Armstrong number.")
else:
print("The number is not 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.

num = int(input("Enter a number: "))


# Check for edge cases first
if num <= 1:
print("The number is neither Prime nor Composite.")
else:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print("The number is a Prime number.")
else:
print("The number is a 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

num = int(input("Enter how many terms :"))


first = 0
second = 1
print(first, end = ' ')
print(second, end = ' ')
for a in range(1, num-1):
third = first + second
print(third, end = ' ')
first , second = second , third
print()
#Method-2
n=int(input('Enter number of terms:'))
print(0,end=' ')
a=0
b=1
for i in range(n-1):
a,b=b+a,a
print(a,end=' ')
print()

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.

# Input two numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
# Store original values for LCM calculation
x=a
y=b
# Compute GCD using Euclidean algorithm
while b != 0:
temp = b
b=a%b
a = temp

gcd = a
print("GCD is:", gcd)

# Compute LCM using the relation: LCM = (x * y) // GCD


lcm = (x * y) // gcd
print("LCM is:", lcm)

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

num = int(input("Enter a number to generate its pattern = "))


for i in range(1,num + 1):
for k in range(num-i,0,-1):
print(' ',end=' ')
for j in range(1,i + 1):
print(j, end = " ")
for j in range(i-1,0,-1):
print(j, end = " ")
print()

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

num = int(input("Enter a number to generate its pattern = "))


for i in range(1,num + 1):
for k in range(num-i,0,-1):
print(' ',end=' ')
for j in range(1,i + 1):
print(j, end = " ")
for j in range(i-1,0,-1):
print(j, end = " ")
print()
for i in range(num-1,0,-1):
for k in range(num-i,0,-1):
print(' ',end=' ')
for j in range(1,i + 1):
print(j, end = " ")
for j in range(i-1,0,-1):
print(j, end = " ")
print()

ASSERTION and REASONING based questions.

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

Q1. Which of the following is a valid Python conditional statement?


A. if x > 10 then:
B. if x > 10:
C. if x > 10 {
D. if (x > 10);
Answer: B. if x > 10:

Q2. What is the output of the following code?

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

Q4. What will be the output of this code?

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

Q5. What does the continue statement do in a loop?


A. Stops the loop completely
B. Skips the current iteration
C. Skips all remaining iterations
D. Pauses the loop
Answer: B. Skips the current iteration

Q6. Which statement is used to exit a loop prematurely?


A. continue
B. exit
C. return
D. break
Answer: D. break

Q7. How many times will this loop run?

i=1
while i < 5:
print(i)
i += 1
A. 4
B. 5

Page 22 of 42
C. Infinite
D. 3
Answer: A. 4

Q8. What is the purpose of else with a loop in Python?


A. Runs if loop fails
B. Runs if condition is false at start
C. Runs when loop ends normally without break
D. Not allowed in Python
Answer: C. Runs when loop ends normally without break

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):

Q10. Which keyword is used for multiple conditions in Python?


A. elseif
B. elif
C. else if
D. ifelse
Answer: B. elif

● 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)

● Write a Python program to input a string and determine whether it is a palindrome or


not; convert the case of characters in a string.
For example, 'malayalam' is a palindrome,
but 'tamil' is not a palindrome.

#1st Method for Palindrome


print("1st Method")
s=input("Enter a string:")
if s==s[::-1]:
print(s, 'is Palindrome!')
else:
print(s, 'is not Palindrome!')
#2nd Method for Palindrome
print("2nd Method")
s=input("Enter a string:")
rev = ""
for i in s:
rev = i + rev

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!')

# Convert the case of each character, 1st Method to convert case


s=input("Enter a string to convert case: ")
converted = ''
for ch in s:
if ch.islower():
converted += ch.upper()
elif ch.isupper():
converted += ch.lower()
else:
converted += ch # Keep non-alphabet characters unchanged

print("String after case conversion:", converted)

# Convert the case of each character, 2nd Method to convert case


s=input("Enter a string to convert case: ")
new_s=''
for ch in s:
if ch>='a' and ch<='z':
new_s+=ch.upper()
elif ch>='A' and ch<='Z':
new_s+=ch.lower()
else:
new_s+=ch
print("New string: ", new_s)

# Convert the case of each character, 3rd Method to convert case


s = input("Enter a string: ")
result = ""
for ch in s:
code = ord(ch)
# If lowercase (a-z), convert to uppercase by subtracting 32
if 97 <= code <= 122:

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

print("Converted string:", result)

1 What will be the output of the following statement?


print(14%3**2*4)
(A) 16 (B) 64
(C) 20 (D) 256

Ans. (C) 20
2 Which of the following is the correct identifier?

(A) global (B) Break


(C) def (D) with

Ans. (B) Break


3 Identify the invalid Python statement out of the following options:

(A) print("A",10, end="*") (B) print("A",sep="*", 10)


(C) print("A",10,sep="*") (D) print("A"*10)

Ans. (B) print("A",sep="*", 10)


4 Which of the following operator evaluates to True if the variable on either side
of the operator point towards the same memory location and False
otherwise?

(A) is (B) is not


(C) and (D) or

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’

Ans. A mutable object can be updated whereas an immutable object cannot be


updated.
Mutable object: [1,2] or {1:1,2:2} (Any one)
Immutable object: (1,2) or ‘123’ (Any one)
9 Give two examples of each of the following:
(I) Arithmetic operators (II) Relational operators
Ans. (I) Arithmetic operators: +,-
(II) Relational operators: >, >=
10 State True or False:
“In Python, tuple is a mutable data type”.
Ans. False
11 What will be the output of the following statement?
print(6+5/4**2//5+8)
(A) –14.0 (B) 14.0
(C) 14 (D) –14
Ans. (B) 14.0

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

(a) 14.75 (b)14.0 (c) 15 (d) 15.5

30 If the value of i is 5, the expression i != 6


a. has the value False
b. has the value True
c. sets the value of i to 6
d. sets the value of i to -5
Ans. b. has the value True
31 Which of these Python data structures cannot have duplicate items and does
not support ordering?

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

33 The statement p -= 5 has the same effect as which of these statements?


a. p = 5
b. p = -5
c. p = p - 5
d. p = 5 – p

Ans.: c. p = p - 5

34 Which operator will be evaluated first in this expression?


6 * 3 ** 2 ** 2 / 2
a. *
b. the first ** from the left
c. the second ** from the left
d. /
Ans. c. the second ** from the left

35 What will be the value of this expression:


4 / 2 ** 3 * 2
a. 16.0
b. 1.0
c. 1/4
d. 1/16

Ans.: b. 1.0

36 Sonal wrote the following program print_students.py to print the number of


students in her class.
class = 5

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)

Ans.: c. changing the variable name ('class' is a reserved word)

37 In python, the term mutable means:


a. memory-efficient
b. fixed
c. changeable
d. sequential
Ans.: c. changeable

38 What will be the output of this program?


m=1
n = "1"
print (str(m) + n)
a. 1
b. 2
c. 11
d. Syntax Error
Ans.: c. 11

39 What will be the output of this Python line?

print("This is Delhi. # Delhi is the capital of India.") # This is a comment.


a. This is Delhi.
b. This is Delhi. # Delhi is the capital of India. # This is a comment.
c. This is Delhi. # Delhi is the capital of India.
d. This is Delhi. This is a comment.

Page 31 of 42
Ans.: c. This is Delhi. # Delhi is the capital of India.

40 What will be the output of this program?


p = "12"
q = "5"
r = 10
s=8
print(p+q, r+s)
a. 17 18
b. 125 108
c. 17 108
d. 125 18
Ans.: d. 125 18
41 What will be the value of p and r at the end of this program?
p = 40
r = 50
p=p+r
r=p-r
p=p-r
print (p, r)
a. p = 40, r = 40
b. p = 50, r = 50
c. p = 50, r = 40
d. p = 40, r = 50
Ans.: c. p = 50, r = 40

42 Find the invalid identifier from the following


a. none
b. address
c. Name
d. pass
Ans.: d. pass

43 Consider a declaration L = (1, 'Python', '3.14').


Which of the following represents the data type of L?
a. list
b. tuple
c. dictionary
d. string
Ans.: b. tuple

44 The return type of the input() function is


a. string

Page 32 of 42
b. integer
c. list
d. tuple
Ans.: a. string

45 Which one of the following is the default extension of a Python file?


a. .exe
b. .p++
c. .py
d. .p
Ans.: c. .py

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

48 Which of the following options is/are not Python Keywords ?


(A) False
(B) Math
(C) WHILE
(D) break
Ans.:
(B) Math and (C) WHILE
49 Identify the statement(s) from the following options which will give Error:
(A) print('5' * 3)
(B) print( 5 * 3)
(C) print('5' + 3)
(D) print('5' + '3')
Ans. (C) print('5' + 3)
50 Identify the valid relational operator(s) in Python from the following : 1
(A) =
(B) <
(C) <>

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

Reason: variable name in Python cannot start with a digit


(b) Which of the following are keywords in Python:
(i) break (ii) check (iii) range (iv) while
Ans.:
(i) break
(iii) range
(iv) while
58 (a) Write the names of the immutable data objects from the following:
(i) List (ii) Tuple (iii) String (iv) Dictionary
Ans.: (ii) Tuple (iii) String
59 (a) Which of the following is valid arithmetic operator in Python:

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')

Ans. W=input('Enter a word') #Error 1


if W == 'Hello' : #Error 2,Error 3
print('Ok')
else : #Error 4
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)

62 Identify the correct output of the following code snippet:


game='Olymic2024'
print(game.index("C"))

Page 35 of 42
(A) 0 (B) 6
(C) -1 (D) ValueError

Ans. (D) ValueError


63 Identify the output of the following code snippet:
text = "PYTHONPROGRAM"
text=text.replace('PY','#')
print(text)
(A) #THONPROGRAM
(B) ##THON#ROGRAM
(C) #THON#ROGRAM
(D) #YTHON#ROGRAM
Ans. (A) #THONPROGRAM
64 What is the output of the expression?
str='International'
print(str.split("n"))
(A) ('I', 'ter', 'atio', 'al')
(B) ['I', 'ter', 'atio', 'al']
(C) ['I', 'n', 'ter', 'n', 'atio', 'n', 'al']
(D) Error
Ans. (B) ['I', 'ter', 'atio', 'al']
65 What will be the output of the following code snippet?
str= "World Peace"
print(str[-2::-2])
Ans. ce lo
66 Select the correct output of the code:
S = "text#next"
print(S.strip("t"))
(A) ext#nex (B) ex#nex
(C) text#nex (D) ext#next
Ans. (A) ext#nex
67 Consider the statements given below and then choose the correct output from the
given options:
Game="World Cup 2023"
print(Game[-6::-1])

(A) CdrW (B) ce o


(C) puC dlroW (D) Error

Ans. (C) puC dlroW


68 Predict the output of the Python code given below:
s="India Growing"

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)

Ans. iIDIA@gGroIiG #Considering capital O in the 7th line of code


OR
i@DIA@gGroI@G #Considering small o in the 7th line of code

69 Consider the statements given below and then choose the correct output from the
given options:

myStr="MISSISSIPPI"
print (myStr[:4] +" # "+myStr[-5:] )

(a) MISSI#SIPPI (b) MISS#SIPPI


(c) MISS#IPPIS (d) MISSI#IPPIS

Ans.: (b) MISS # SIPPI


70 Select the correct output of the following code:

event="G20 Presidency@2023"
L=event.split(' ')
print(L[::-2])

(a) 'G20' (b) ['Presidency@2023']


(c) ['G20'] (d) 'Presidency@2023'

Ans. (b) ['Presidency@2023']


71 Q. 18 is ASSERTION (A) and REASONING (R) based questions.

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

73 Write the output on execution of the following Python code:


S="Racecar Car Radar"
L=S.split()
for W in L:
x=W.upper()
if x==x[::-1]:
for I in x:
print(I,end="*")
else:
for I in W:
print(I,end="#")
print()

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

77 Predict the output of the Python code given below:

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) Year . 0. at All the best


(b) Year 0. at All the best
(c) Year . 022. at All the best
(d) Year . 0. at all the best

Ans. (a) Year . 0. at All the best


83 Which of the following statement(s) would give an error after
executing the following code?

S="Welcome to class XII" # Statement 1


print(S) # Statement 2
S="Thank you" # Statement 3
S[0]= '@' # Statement 4
S=S+"Thank you" # Statement 5

(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5

Ans. (b) – Statement 4


84 (a) Given is a Python string declaration:

myexam="@@CBSE Examination 2022@@"

Write the output of: print(myexam[::-2])

Ans. @20 otnmx SC@


85 Predict the output of the code given below:

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

You might also like