WHY BRAIN BUSTERS
SERIES?
Dear Maharathi,
Are you ready to unlock the secrets of Computer Science and conquer
every challenge that comes your way? If you're looking for a one-stop
guide that will make your Class 12 Computer Science exam preparation
smooth, powerful, and rewarding, then this book is for you!
The Brain Buster Series is not just another textbook—it's your ultimate
companion for mastering the key concepts, boosting your problem-
solving skills, and acing your exam with confidence. We’ve crafted this
series to make sure that every student, whether you're a beginner or
already ahead of the curve, will find something valuable to learn and
grow from.
Here's why you can't afford to miss this book:
1. Comprehensive Coverage of the Syllabus
Every question in this series is meticulously designed to cover the entire
Class 12 Computer Science syllabus. From Python programming to SQL
and data structures, we’ve got you covered. No topic is left untouched,
ensuring that you're fully prepared to tackle any question that comes
your way.
2. Challenging Yet Rewarding
The Brain Buster Series is packed with output-based questions, logical
challenges, and coding exercises that will test your limits and sharpen
your skills. Each question is a brain teaser designed to stimulate your
thinking, enhance your coding abilities, and prepare you for the
toughest exam questions.
3. Instant Understanding with Solutions
After every set of questions, you’ll find detailed explanations that
break down complex problems into simple steps. This allows you to
understand the 'why' behind the answers—so you don’t just
memorize solutions, but genuinely grasp the concepts.
4. Real-World Relevance
We don’t just focus on exams—we focus on making you industry-
ready. Learn how these topics come to life in the real world, and
develop skills that will serve you not only in exams but also in your
future career.
5. A Fun & Interactive Learning Experience
The best part? We’ve made learning fun! With interactive exercises,
quizzes, and challenges, studying doesn’t have to be boring. Feel the
satisfaction of cracking a tough question and growing your
confidence as you move through the series. It’s not just about grades
—it’s about becoming a Computer Science master.
6. Your Path to Exam Success
We know Class 12 is a critical year, and exams can be stressful. But
with the Brain Buster Series, you’ll have a solid strategy to approach
each question with confidence. You’ll no longer feel overwhelmed;
instead, you'll feel ready—with practice that’s both effective and
engaging.
Why Should You Get This Book?
Because you deserve to succeed, Maharathi.
Because you deserve to have the confidence to walk into your exam
room, knowing you’ve got the skills to dominate.
Because this book is designed to make YOU the winner, and we
believe that with a little guidance and the right approach, you will be
unstoppable.
#maharathiMaterial
CLASS 12
COMPUTER SCIENCE
OUTPUT-BASED
QUESTIONS
WITH SOLUTIONS
Tips and Tricks for Solving
Output-Based Questions
For Beginners
1. Understand the Code Structure:
Read the code carefully and identify the flow, such as
loops, conditional statements, and function calls.
Pay attention to indentation, as it defines code blocks in
Python.
2. Learn the Basics of Python:
Understand data types (e.g., int, str, list) and their
operations.
Familiarize yourself with Python's built-in functions like
len(), print(), range(), split(), etc.
3. Operator Precedence:
Remember the PEDMAS rule for arithmetic operations:
Parentheses > Exponents > Division>Multiplication >
Addition>Subtraction.
For logical operations: not > and > or.
4. Focus on Indexing and Slicing:
Zero-based indexing is key for lists, strings, and tuples.
Slicing syntax: start:end:step—understand how the step
modifies the slicing.
5. Trace the Code Line-by-Line:
Use pen and paper to write down the changes in variables
and data structures as the code executes.
6. Beware of Mutable and Immutable Data:
Lists and dictionaries are mutable (can change in place).
Strings and tuples are immutable (cannot change once
created).
For Intermediate Learners
Analyze Loop Behaviors:
Understand how range(start, stop, step) works.
Pay close attention to nested loops and their order of
execution.
Master Function Behavior:
Identify the difference between return and print.
Understand function scope: local vs. global variables.
Learn about default arguments in function definitions.
File Handling Nuances:
Observe how read(), readline(), and readlines() behave.
Understand modes like 'r', 'w', 'a', and how they impact file
operations.
Understand List Comprehensions:
Practice converting for-loops into list comprehensions
and vice versa.
Understand conditional comprehensions, e.g., [x for x in lst
if x % 2 == 0].
Bitwise and Logical Operators:
Grasp the working of &, |, ^, <<, and >> operators.
Use truth tables to understand logical combinations of
True and False.
Common Built-in Functions:
Memorize key functions like map(), filter(), zip(), and
enumerate().
For Advanced Learners
Edge Cases are Key:
Anticipate special cases like empty lists, dividing by zero,
or accessing out-of-range indices.
Optimize Recursion:
For recursive functions, trace calls with a stack-like
diagram to track intermediate values.
Understand Error Handling:
Learn to identify try-except blocks and predict exception
flow.
Familiarize yourself with common errors like IndexError,
KeyError, and ZeroDivisionError.
Lambda Functions and Shortcuts:
Understand how lambda works in combination with
functions like sorted() or filter().
Deep Dive into Python Objects:
Grasp how mutable objects like lists behave when passed
to functions.
Understand how Python manages memory (e.g., reference
vs. value).
Advanced Data Structures:
Practice with nested lists, dictionaries, and tuples.
Use unpacking techniques: a, b = (1, 2) or *rest, last = [1, 2,
3, 4].
Pythonic Debugging Techniques:
Use print() statements or the pdb module to debug and
trace code execution.
Keep an Eye on String Formatting:
Practice f-strings, format(), and %-style formatting.
General Tips for All Levels
Run the Code:
Use an IDE or online Python interpreter to test snippets of
code and verify your predictions.
Break Down Complex Problems:
Divide the code into smaller logical chunks and solve each
part step by step.
Keep Practicing:
Regularly solve a mix of easy and tricky questions to build
confidence.
Watch for Hidden Traps:
Pay close attention to special cases, such as:
Overwriting variables unintentionally.
Using the wrong operator (e.g., = instead of ==).
Infinite loops due to incorrect conditions.
Learn from Mistakes:
Analyze why you got a question wrong and ensure you
understand the concept fully.
Arithmetic and Logical
Operators Ques 6. Evaluate the output:
import randomfruits = ['Apple',
'Banana', 'Cherry']
Ques 1. What will be the output of for i in range(3):
the following code? print(fruits[random.
print(10 + 3 * 2 - 5 / 5) randrange(len(fruits))], end='-')
(a) 25.0 (a) Random fruit names separated
(b) 13.0 by -
(c) 14.0 (b) Error
(d) 15.0 (c) None
(d) Apple-Banana-Cherry
Ques 2. Evaluate the output:
a, b = 4, 8
String Manipulation
print(a & b, a | b, a ^ b)
(a) 0, 12, 12
Ques 7. Determine the output:
(b) 0, 12, 4
S = "ComputerScience"
(c) 0, 12, 8
print(S[:5] + S[-5:])
(d) Error
(a) Compuience
(b) Compute
Ques 3. Determine the output:
(c) Computence
print(15 > 10 or 5 < 3 and 8 >= 8)
(d) Error
(a) True
(b) False
Ques 8. What is displayed by the
(c) Error
code?
(d) None
S = "HELLO PYTHON"
print(S.split()[1][::-1])
Ques 4. What is displayed by the
(a) NOTHYP
following?
(b) NOHTYP
print(4 << 2, 16 >> 3)
(c) NOHTYP
(a) 16, 2
(d) PYTHON
(b) 8, 3
(c) 16, 3
Ques 9. Predict the output:
(d) 8, 2
S = "MISSISSIPPI"
print(S[0:4] + '-' + S[-4:])
Random Module and Looping (a) MISS-IPPI
(b) MISS-SIPPI
Ques 5. Predict the output of this (c) MISS-PPI
code: (d) None
import random
nums = [5, 10, 15, 20] Lists
for i in range(2):
print(random.choice(nums), Ques 10. What will this display?
end=" ") lst = [100, 200, 300, 400]
(a) 5 10 print(lst[1::2])
(b) Random output from nums (a) [200, 400]
twice (b) [100, 300]
(c) Error (c) [200]
(d) 5 5 (d) None
Ques 11. Output for the following
Ques 16. Predict the output:
code:
with open("data.txt", "w") as f:
lst = ['A', 'B', 'C', 'D']
print(lst[-1::-3]) f.writelines(["Line1\n", "Line2\n",
(a) ['D'] "Line3\n"])
(b) ['D', 'A']
(c) ['D', 'B'] with open("data.txt", "r") as f:
(d) Error for line in f.readlines():
print(line.strip())
Ques 12. Evaluate this output:
L1 = [10, 20, 30] (a) Line1 Line2 Line3
print(L1.pop(), L1.pop(), L1.pop()) (b) Line1\nLine2\nLine3\n
(a) 10 20 30 (c) Line1, Line2, Line3
(b) 30 20 10 (d) None
(c) 30 10 20
(d) Error Functions, Recursion, and More
Functions and Scoping Ques 17. What will be the output of the
following code?
Ques 13. Predict the output:
def add(a, b):
x = 50
return a + b
def modify():
x = 25 result = add(5, 10)
modify() print(result)
print(x) (a) 15
(a) 50 (b) 510
(b) 25 (c) 5
(c) Error (d) Error
(d) None
Ques 18. Determine the output:
Ques 14. What is displayed by this code?
def recurse(n):
def calc(a, b):
if n == 0:
return a + b, a * b
x, y = calc(2, 3) return 0
print(x, y) else:
(a) 5, 6 return n + recurse(n-1)
(b) 5, 5 print(recurse(3))
(c) Error (a) 3
(d) 6, 5 (b) 6
(c) 0
File Handling
(d) Error
Ques 15. Output for the following:
f = open("test.txt", "w") Ques 19. What does the following code
f.write("Hello\nPython") print?
f.close()f = open("test.txt", "r") multiply = lambda x, y: x * y
print(f.readline().strip()) print(multiply(4, 5))
f.close() (a) 20
(a) Hello
(b) 9
(b) Python
(c) 45
(c) HelloPython
(d) None (d) 54
coordinates = (10, 20)
Ques 20. Find the output of the
x, y = coordinates
following code:
print(x, y)
numbers = [1, 2, 3, 4]
(a) 10 20
squares = [x**2 for x in numbers]
(b) (10, 20)
print(squares)
(c) x y
(a) [1, 4, 9, 16]
(d) Error
(b) [2, 4, 6, 8]
(c) [1, 2, 3, 4]
Ques 25. Find the output:
(d) [1, 8, 27, 64]
A = {1, 2, 3}
B = {2, 3, 4}
Ques 21. What will be printed by the
print(A.union(B), A.intersection(B))
following code?
(a) {1, 2, 3, 4} {2, 3}
D = {'a': 1, 'b': 2, 'c': 3}
(b) {1, 2, 3} {1}
print(D.get('b'), D.get('d', 4))
(c) {2, 3, 4} {1, 4}
(a) 2 4
(d) {1, 2, 3, 4} {1, 2}
(b) 2 None
(c) 1 4
Ques 26. What does the following
(d) Error
code output?
with open("test.txt", "w") as f:
Ques 22. What is the output of the
f.write("Hello\nWorld")
following code?
with open("test.txt", "r") as f:
try:
content = f.read()
print(10 / 0)
print(content)
except ZeroDivisionError:
(a) Hello World
print("Cannot divide by zero")
(b) Hello\nWorld
finally:
(c) Hello followed by World on a new
print("Execution Complete")
line
(a) Cannot divide by zero
(d) Error
(b) Cannot divide by zero followed by
Execution Complete Ques 27. What will be printed by this
(c) Execution Complete code?
(d) Error def outer():
def inner():
Ques 23. Determine the output: return "Inner"
name = "Alice" return inner()
age = 21 print(outer())
print(f"{name} is {age} years old.") (a) Outer
(a) Alice is 21 years old. (b) Inner
(b) name is age years old. (c) Error
(c) Alice is age years old. (d) None
(d) Error
Ques 28. Determine the output:
Ques 24. What will the following code def factorial(n):
print?
Ques 33. What is the output of the
if n == 1: following code?
return 1 s = "hello world"
else: print(s.capitalize(), s.upper())
return n * factorial(n-1) (a) Hello world HELLO WORLD
print(factorial(4)) (b) hello world HELLO WORLD
(a) 24 (c) HELLO WORLD Hello world
(b) 12 (d) Error
(c) 6
(d) Error Ques 34. What will the code print?
def func(a, b=5):
Ques 29. What is the output of the return a + b
following code? print(func(3))
lst = [1, 2, 3] (a) 8
lst.append([4, 5]) (b) 3
print(lst) (c) 5
(a) [1, 2, 3, 4, 5] (d) Error
(b) [1, 2, 3, [4, 5]]
(c) [1, 2, 3] Ques 35. Determine the output:
(d) Error def func(n):
if n == 0:
Ques 30. Find the output: return 0
s = "DataStructures" else:
print(s[4:10]) return n + func(n-2)
(a) Structures print(func(5))
(b) Structures (a) 5
(c) Struc (b) 6
(d) Struct (c) 9
(d) Error
Ques 31. What will be printed by the
following code? Ques 36. What does the following code
a = True print?
b = False keys = ['a', 'b', 'c']
print(a and b, a or b, not a, not b) values = [1, 2, 3]
(a) False True False True D = {k: v for k, v in zip(keys, values)}
(b) True False True False print(D)
(c) False False True True (a) {'a': 1, 'b': 2, 'c': 3}
(d) True True False False (b) ['a', 1, 'b', 2, 'c', 3]
(c) {'a': '1', 'b': '2', 'c': '3'}
Ques 32. Determine the output: (d) Error
lst = ['Python', 'Java', 'C++']
print(lst[2], lst[-1])
(a) C++ C++
(b) C++ Java
(c) Java C++
(d) Error
Advanced Topics Ques 41. Find the output:
lst = [10, 20, 30, 40, 50, 60]
Ques 37. Find the output: print(lst[::2])
matrix = [[1, 2], [3, 4]] (a) [10, 30, 50]
print(matrix[0][1], matrix[1][0]) (b) [10, 20, 30]
(a) 2 3 (c) [20, 40, 60]
(b) 1 4 (d) [10, 30, 50, 70]
(c) 3 2
(d) Error Ques 42. What does the following
code print?
Ques 38. What is printed by the t = (1, 2, 3)
following code? t += (4,)
s = "banana" print(t)
print(s.replace('a', 'o')) (a) (1, 2, 3, 4)
(a) bonono (b) (1, 2, 3)
(b) banana (c) (4,)
(c) None (d) Error
(d) Error
Ques 43. Determine the output:
Ques 39. Determine the output: D = {'x': 10, 'y': 20}
A = {1, 2, 3} print(D['x'] + D.get('y'))
B = {3, 4, 5} (a) 30
print(A - B, B - A) (b) 20
(a) {1, 2} {4, 5} (c) Error
(b) {3} {3} (d) 10
(c) {1, 2, 3} {3, 4, 5}
(d) Error Ques 44. What will the following
code output?
Ques 40. What will be the output? for i in range(3):
def greet(name, msg="Good if i == 1:
morning!"): continue
print(msg, name) print(i, end=' ')
(a) 0 1 2
greet("Alice") (b) 0 2
greet("Bob", "Hello") (c) 1
(a) (d) 0 1
Good morning! Alice
Hello Bob Ques 45. What is the output of this
(b) code?
Hello Alice def recursive_sum(n):
Good morning! Bob if n == 0:
(c) return 0
Good morning! Alice else:
Good morning! Bob return n + recursive_sum(n-1)
(d) Error print(recursive_sum(2))
Ques 49. What does the following
(a) 3 code output if data.txt contains:
(b) 2 Line1
(c) 1 Line2
(d) 0 Line3
Ques 46. Find the output:
s = "Data Science" with open("data.txt", "r") as f:
print(s.split()) for line in f:
(a) ['Data', 'Science'] print(line.strip())
(b) 'Data Science' (a)
(c) ['D', 'a', 't', 'a', ' ', 'S', 'c', 'i', 'e', 'n', Line1
'c', 'e'] Line2
(d) Error Line3
(b) Line1 Line2 Line3
Ques 47. What will be printed by (c) ['Line1', 'Line2', 'Line3']
the following code? (d) Error
lst = [1, 2, 3]
lst[1] = lst[2] + lst[0] Ques 50. Find the output:
print(lst) numbers = [1, 2, 3, 4, 5]
(a) [1, 4, 3] even_squares = [x**2 for x in
(b) [1, 5, 3] numbers if x % 2 == 0]
(c) [1, 2, 3] print(even_squares)
(d) Error (a) [1, 4, 9, 16, 25]
(b) [4, 16]
Ques 48. Determine the output: (c) [2, 4]
x=5 (d) Error
def func():
Ques 51. What will be the output of
x = 10
the following code?
print(x)
x, y, z = 5, 10, 15
func()
result = x * y / z + x
print(x)
print(result)
(a) 5.0
(a)
(b) 10.0
10
(c) 15.0
5
(d) 20.0
(b)
Ques 52. Predict the output:
10
S = "Information"
10
print(S[3:8] + S[-3:])
(a) ormatn
(c)
(b) ormatton
5
(c) ormatoin
10
(d) Error
(d) Error
Ques 58. Determine the output:
Ques 53. What will this print? text = "Python Programming"
S = "HELLO" print(text.lower().replace("python",
print(S[-3], S[2]) "Java"))
(a) L L (a) Java programming
(b) L O (b) Python programming
(c) E L (c) java Programming
(d) Error (d) Error
Ques 54. Determine the output: Ques 59. Predict the output:
for i in range(1, 3): f = open("sample.txt", "w")
for j in range(i, 4): f.write("Hello\nWorld")
print(i * j, end=" ") f.close()
(a) 1 2 3 2 4 6
(b) 1 2 3 4 6 f = open("sample.txt", "r")
(c) 1 4 2 6 3 print(f.read())
(d) Error f.close()
(a) Hello World
Ques 55. Find the output of the (b) Hello\nWorld
code: (c) Hello followed by World on a new
lst = [1, 3, 5, 7] line
lst.insert(2, 9) (d) Error
print(lst)
(a) [1, 3, 9, 5, 7] Ques 60. Find the output:
(b) [1, 9, 3, 5, 7] lst = [10, 20, 30, 40, 50]
(c) [1, 3, 5, 7, 9] print(lst[1::2])
(d) Error (a) [20, 40]
(b) [10, 20]
Ques 56. Predict the output: (c) [30, 50]
D = {'a': 1, 'b': 2, 'c': 3} (d) Error
del D['b']
print(D) Ques 61. What will this display?
(a) {'a': 1, 'b': 2} tup = (1, 2, 3)
(b) {'a': 1, 'c': 3} tup += (4,)
(c) {'c': 3} print(tup)
(d) Error (a) (1, 2, 3, 4)
(b) (1, 2, 3)
Ques 57. What will this print? (c) (4,)
x = 42 (d) Error
print(f"The value of x is {x}.")
(a) The value of x is 42. Ques 62. Determine the output:
(b) 42 is the value of x. def sum_up(n):
(c) The value of x is x. if n == 0:
(d) Error return 0
return n + sum_up(n - 1)
Ques 67. Evaluate the output:
print(sum_up(3))
a, b = True, False
(a) 6
print(a and b, a or b, not a)
(b) 3
(a) False True False
(c) 9
(b) True False True
(d) Error
(c) False True True
(d) Error
Ques 63. Find the output:
try: Ques 68. What will this display?
print(10 / 0) f = open("data.txt", "w")
except ZeroDivisionError: f.write("Line1\nLine2")
print("Error occurred") f.close()
finally: f = open("data.txt", "r")
print("Done") print(f.readlines())
(a) Error occurred Done f.close()
(b) Error occurred (a) ['Line1\n', 'Line2']
(c) Done (b) Line1\nLine2
(d) Error (c) ['Line1', 'Line2']
(d) Error
Ques 64. What does the following print?
lst = [1, 2, 3] Ques 69. Find the output:
lst[1] = lst[2] + lst[0] s = "Python"
print(lst) print(s.center(10, '-'))
(a) [1, 4, 3] (a) --Python--
(b) [1, 5, 3] (b) Python----
(c) [1, 2, 3] (c) --Python
(d) Error (d) Error
Ques 65. Predict the output: Ques 70. Predict the output:
s1, s2 = "Good", "Morning" lst = [1, 2, 3]
print(s1 + " " + s2) print(len(lst), max(lst), min(lst))
(a) GoodMorning (a) 3 3 1
(b) Good Morning (b) 3 1 3
(c) Good Morning (c) 1 3 3
(d) Error (d) Error
Ques 66. What will this code output? Ques 71. What will this display?
def outer(): def factorial(n):
def inner(): if n == 1:
return "Inner"return inner() return 1
else:
print(outer()) return n * factorial(n - 1)
(a) Inner print(factorial(5))
(b) Outer (a) 120
(c) Error (b) 5
(d) None (c) 25
(d) Error
Ques 72. Determine the output: Ques 77. Predict the output of this
matrix = [[1, 2], [3, 4]] code:
print(matrix[0][1], matrix[1][0]) words = ["I", "love", "Python"]
(a) 2 3 print(" ".join(words))
(b) 1 4 (a) I love Python
(c) 3 2 (b) I lovePython
(d) Error (c) IlovePython
(d) Error
Ques 73: What does the following code
print?
Ques 78. What will this code display?
import math
D = {"A": {"B": 5}, "C": 10}
print(math.sqrt(16), math.ceil(4.2))
print(D["A"]["B"])
(a) 4.0 4
(a) 5
(b) 4.0 5
(c) 16 5 (b) 10
(d) Error (c) Error
(d) None
Ques 74: Predict the output:
x = 10 Question 79: Determine the output:
y = "20" S = "DataScience"
print(x + int(y)) print(S[::-2])
(a) 1020 (a) ecntea
(b) 30 (b) eniStD
(c) Error (c) eictD
(d) None (d) Error
Ques 75. What will this display? Ques 80. Predict the output:
f = open("file.txt", "w") for i in range(1, 4):
f.write("Hello\nWorld") for j in range(2, 5, 2):
f.close() print(i * j, end=", ")
f = open("file.txt", "r")
(a) 2, 4, 6, 6, 8, 12, 8, 12, 16,
for line in f:
(b) 2, 4, 4, 8, 6, 12,
print(line.strip())
(c) 2, 4, 6, 6, 12,
f.close()
(d) Error
(a) Hello World
(b) Hello followed by World on separate
lines Ques 81. What will the following
(c) Error print?
(d) None double = lambda x: x * 2
print(double(7))
Ques 76. What will the following code (a) 14
print? (b) 7
S = "Learning" (c) 14.0
print(S[-5:]) (d) Error
(a) rning
(b) Learn
(c) ing
(d) Error
Ques 82. Find the output:
def custom_sum(n): (a) Python
if n % 2 == 0: (b) Programming
return n (c) Python Programming
return n + custom_sum(n - 2) (d) Error
print(custom_sum(5)) Ques 87. What will the following code
(a) 15 output?
(b) 5 text = "Programming is fun"
(c) 9 print(text.replace("fun", "amazing"))
(d) Error (a) Programming is amazing
(b) Programming is fun
Ques 83: Determine the output: (c) Programming amazing
name = "CBSE Computer Science" (d) Error
print(name.count('e'))
(a) 3 Ques 88. What will this print?
(b) 2 t = (10, 20, 30, 40)
(c) 1 print(t[1:3])
(d) Error (a) (20, 30)
(b) [20, 30]
(c) (10, 40)
Ques 84. Predict the output: (d) Error
s = "Hello"
print(s * 2) Ques 89. Find the output:
(a) HelloHello def greet(name="Guest"):
(b) Hello return f"Hello, {name}!"
(c) Error print(greet("Alice"))
(d) Hello2 print(greet())
(a) Hello, Alice! followed by Hello,
Ques 85. Find the output of this code: Guest!
lst = [5, 10, 15] (b) Hello, Alice! followed by Error
lst.reverse() (c) Hello, Guest! twice
print(lst) (d) Error
(a) [15, 10, 5]
(b) [5, 15, 10] Ques 90. What is displayed by this
(c) [5, 10, 15] code?
(d) Error numbers = [10, 5, 15]
numbers.sort()
Ques 86. What does this print? print(numbers)
f = open("example.txt", "w") (a) [5, 10, 15]
f.write("Python\nProgramming") (b) [10, 5, 15]
f.close() (c) [15, 10, 5]
f = open("example.txt", "r") (d) Error
print(f.readline().strip())
f.close()
Ques 91. Predict the output: (a) ['Python', 'Programming']
print(5 > 3 and 3 < 2 or 10 == 10) (b) ['PythonProgramming']
(a) True (c) ['Python\nProgramming']
(b) False (d) Error
(c) None
(d) Error Ques 96. Find the output of this code:
D = {"a": 10, "b": 20, "c": 30}
Question 92: Find the output: print(D.get("b", 0), D.get("d", 0))
with open("data.txt", "w") as f: (a) 20 0
f.writelines(["Hello\n", "World\n", (b) 10 0
"Python\n"]) (c) 30 20
(d) Error
with open("data.txt", "r") as f:
print(f.readlines()) Ques 97. Predict the output:
(a) ['Hello\n', 'World\n', 'Python\n'] for i in range(4):
(b) Hello\nWorld\nPython\n if i == 2:
(c) Error continue
(d) None print(i, end=", ")
(a) 0, 1, 3,
Ques 93. Find the output: (b) 0, 1, 2, 3,
lst = [10, 20, 30, 40, 50] (c) 1, 3,
print(lst[::3]) (d) Error
(a) [10, 40]
(b) [10, 30, 50] Ques 98. What will this display?
(c) [10, 50] numbers = [1, 2, 3, 4, 5]
(d) Error result = [x**2 for x in numbers if x % 2 ==
0]
Ques 94. Predict the output: print(result)
A = {1, 2, 3} (a) [4, 16]
B = {3, 4, 5} (b) [2, 4]
print(A | B, A & B) (c) [1, 4, 9]
(a) {1, 2, 3, 4, 5} {3} (d) Error
(b) {1, 2, 3} {4, 5}
(c) {3} {3} Ques 99: What will be displayed?
(d) Error tuple1 = (1, 2, 3)
tuple1[0] = 4
Ques 95. What will this print? print(tuple1)
f = open("data.txt", "w") (a) (4, 2, 3)
f.write("Python\nProgramming") (b) (1, 2, 3)
f.close() (c) Error
(d) None
f = open("data.txt", "r")
print(f.read().split()) Ques 100. What does this print?
s = "Mississippi"
print(s.count("s"))
(a) 4
(b) 2
(c) 1
(d) Error
Ques 101. Predict the output:
def square(n):
return n * n
def double(n):
return n + n
print(square(double(3)))
(a) 36
(b) 12
(c) 18
(d) Error
SOLUTIONS
QUESTION 1: FINAL OUTPUT:
print(10 + 3 * 2 - 5 / 5) The result is 15.0 (a floating-
point number). However,
Answer: (d) 15.0 Python’s default behavior when
printing a float without
CONCEPT INVOLVED: formatting retains the decimal
PEMDAS Rule: point.
Operator precedence in Python follows
this order: KEY POINTS TO REMEMBER:
Parentheses (P): Operations inside Order of Operations (PEMDAS):
parentheses are evaluated first. Always start with higher-
Exponents (E): Exponentiation (**) is precedence operators before
evaluated next. moving to addition or
Multiplication/Division (MD): Evaluated subtraction.
from left to right as they appear. Division results in a floating-
Addition/Subtraction (AS): Evaluated point value (/ always outputs a
last, from left to right. float in Python).
Subtraction involving a float (like
STEP-BY-STEP EVALUATION 16 - 1.0) retains the floating-
Expression: point representation.
10 + 3 * 2 - 5 / 5
No parentheses (P) or exponents (E), so
we move to Multiplication and Division.
Step 1 - Evaluate 3 * 2:
QUESTION 2:
3*2=6 a, b = 4, 8
Updated expression: print(a & b, a | b, a ^ b)
10 + 6 - 5 / 5
Step 2 - Evaluate 5 / 5: Answer: (a) 0, 12, 12
5 / 5 = 1.0
Updated expression: CONCEPT INVOLVED:
10 + 6 - 1.0 Bitwise Operators:
Step 3 - Perform Addition (10 + 6): & (AND): Compares each bit
10 + 6 = 16 and returns 1 if both bits are 1,
Updated expression: otherwise 0.
16 - 1.0 | (OR): Compares each bit and
Step 4 - Perform Subtraction (16 - 1.0): returns 1 if at least one bit is 1.
16 - 1.0 = 15.0 ^ (XOR): Compares each bit
and returns 1 if the bits are
different, otherwise 0.
STEP-BY-STEP EVALUATION:
Binary Representation: not
and
a = 4 → 0100 (binary)
or (evaluated last).
b = 8 → 1000 (binary)
Logical expressions are short-
Step 1 - a & b (Bitwise AND): circuited, meaning Python
Perform bitwise AND: stops evaluating once the final
0100 & 1000 = 0000 result is determined.
Decimal equivalent: 0
Step 2 - a | b (Bitwise OR): STEP-BY-STEP EVALUATION:
Perform bitwise OR: Expression:
0100 | 1000 = 1100 15 > 10 or 5 < 3 and 8 >= 8
Decimal equivalent: 12 Step 1 - Evaluate Comparison
Operators:
Step 3 - a ^ b (Bitwise XOR):
15 > 10 → True
Perform bitwise XOR:
5 < 3 → False
0100 ^ 1000 = 1100 8 >= 8 → True
Decimal equivalent: 12 Updated expression:
True or False and True
FINAL OUTPUT: Step 2 - Apply and (evaluated
The output is 0, 12, 12. before or):
False and True → False
KEY POINTS TO REMEMBER: Updated expression:
Bitwise AND (&): Returns 1 if both bits True or False
Step 3 - Apply or:
are 1.
True or False → True
Bitwise OR (|): Returns 1 if at least one
bit is 1. FINAL OUTPUT:
Bitwise XOR (^): Returns 1 if the bits The result of the logical expression
are different. is True.
Binary operations are performed bit
by bit on the binary representations KEY POINTS TO REMEMBER:
of the numbers. Logical operators are evaluated in
the order: not > and > or.
Short-circuiting:
For or, if the first operand is
QUESTION 3:
True, the rest is not evaluated.
print(15 > 10 or 5 < 3 and 8 >= 8) For and, if the first operand is
False, the rest is not evaluated.
Answer: (a) True Comparison operators (<, >, >=, etc.)
are evaluated first, before logical
CONCEPT INVOLVED: operators.
Logical Operators and Precedence:
Python evaluates logical
operators (or, and, not) in the
following order:
KEY POINTS TO REMEMBER:
QUESTION 4:
Left Shift (<<): Multiplies the
print(4 << 2, 16 >> 3)
number by 2^n (where n is the
number of shifts).
Answer: (a) 16, 2
Example: 4 << 2 = 4 * 2^2 = 16.
Right Shift (>>): Divides the number
CONCEPT INVOLVED:
by 2^n (integer division).
Bitwise Shift Operators:
Example: 16 >> 3 = 16 // 2^3 = 2.
Left Shift (<<): Shifts the bits of a
Binary representations are useful
number to the left, filling with
for visualizing bitwise operations.
zeros on the right. Each shift to
the left is equivalent to
multiplying the number by 2.
Right Shift (>>): Shifts the bits of QUESTION 5:
a number to the right, discarding import random
the rightmost bits. Each shift to nums = [5, 10, 15, 20]
the right is equivalent to dividing for i in range(2):
the number by 2 (integer print(random.choice(nums),
division). end=" ")
STEP-BY-STEP EVALUATION: Answer: (b) Random output from
Expression: nums twice
4 << 2 and 16 >> 3
Step 1 - Evaluate 4 << 2 (Left Shift): CONCEPT INVOLVED:
Binary representation of 4 is random.choice():
100. This function randomly selects
Shifting left by 2 adds two zeros an element from the given
to the right: sequence (nums in this case).
100 → 10000 Each call to
10000 in binary is 16 in decimal. random.choice(nums) is
Step 2 - Evaluate 16 >> 3 (Right independent, meaning the
Shift): results can vary on every run.
Binary representation of 16 is Loops:
10000. The for loop executes twice
Shifting right by 3 removes three (range(2)), calling
rightmost bits: random.choice(nums) in each
10000 → 10 iteration.
10 in binary is 2 in decimal.
STEP-BY-STEP EVALUATION:
FINAL OUTPUT: Expression:
The output is 16, 2. The list nums is [5, 10, 15, 20].
The loop iterates twice
(range(2)).
print(fruits[random.randrange(len(f
Step 1 - Iteration 1: ruits))], end='-')
The first iteration calls
random.choice(nums) and Answer: (a) Random fruit names
selects a random value from [5, separated by -
10, 15, 20].
Possible outputs: 5, 10, 15, or CONCEPT INVOLVED:
20. random.randrange():
Step 2 - Iteration 2: Generates a random integer
The second iteration calls between 0 (inclusive) and the
random.choice(nums) again, given value (len(fruits) here,
independently selecting another which is 3) exclusive.
random value from [5, 10, 15, Each call to
20]. random.randrange(len(fruits))
Output: independently selects an index
Since random.choice(nums) is from the range [0, 1, 2].
called twice, the output will for Loop:
consist of two randomly The loop iterates 3 times
selected values from the list. (range(3)), printing a randomly
Example: 15 10, 5 5, or any other chosen fruit from the list in each
combination. iteration.
String Formatting in print():
FINAL OUTPUT: The end='-' ensures all fruit
The output will be two random names are printed on the same
values from nums, separated by a line, separated by a -.
space.
STEP-BY-STEP EVALUATION:
KEY POINTS TO REMEMBER: Expression:
random.choice(nums): The list fruits = ['Apple',
Returns a randomly selected 'Banana', 'Cherry'].
element from the list nums. The loop runs 3 times (range(3)).
Each call is independent and can Step 1 - First Iteration:
return the same or different random.randrange(len(fruits))
elements. generates a random index from
range(n): [0, 1, 2].
Creates a sequence of n Example: Randomly selects 0,
iterations. In this case, the loop corresponding to Apple.
runs twice (range(2)). Step 2 - Second Iteration:
random.randrange(len(fruits))
generates another random
QUESTION 6: index.
import random Example: Randomly selects 2,
fruits = ['Apple', 'Banana', 'Cherry'] corresponding to Cherry.
for i in range(3):
STEP-BY-STEP EVALUATION:
Step 3 - Third Iteration: Expression:
random.randrange(len(fruits)) S[:5] + S[-5:]
generates yet another random Step 1 - Evaluate S[:5]:
index. S = "ComputerScience"
Example: Randomly selects 1, S[:5] extracts the first 5
corresponding to Banana. characters: "Compu".
Output: Step 2 - Evaluate S[-5:]:
The result could be something S[-5:] extracts the last 5
like Apple-Cherry-Banana- or characters: "ience".
any other random combination Step 3 - Concatenate the Results:
of fruits. "Compu" + "ience" →
"Compuience"
FINAL OUTPUT:
Random fruit names separated by -. FINAL OUTPUT:
Compuience
KEY POINTS TO REMEMBER:
random.randrange(n): KEY POINTS TO REMEMBER:
Generates a random integer Positive indices (S[:5]) start from the
from 0 to n-1. beginning of the string.
Each call is independent, and Negative indices (S[-5:]) start from
indices may repeat. the end of the string.
Loop Iterations: String slicing is non-destructive and
The for loop ensures the creates a new substring.
operation is performed 3 times.
The end='-' argument in print() adds
a - after each fruit name.
QUESTION 8:
S = "HELLO PYTHON"
print(S.split()[1][::-1])
QUESTION 7: Answer: (b) NOHTYP
S = "ComputerScience"
print(S[:5] + S[-5:]) CONCEPT INVOLVED:
split() Function: Splits a string into a
Answer: (a) Compuience list of words.
Default behavior splits by
CONCEPT INVOLVED: whitespace.
String Slicing: In this case, "HELLO PYTHON" is
S[:n]: Extracts the substring from split into ['HELLO', 'PYTHON'].
the start up to (but not String Reversal:
including) index n. [::-1] reverses the string
S[-n:]: Extracts the last n character by character.
characters of the string.
STEP-BY-STEP EVALUATION: STEP-BY-STEP EVALUATION:
Expression: Expression:
S.split()[1][::-1] S[0:4] + '-' + S[-4:]
Step 1 - Apply split(): Step 1 - Extract S[0:4]:
"HELLO PYTHON".split() S = "MISSISSIPPI"
produces the list: S[0:4] extracts characters from
['HELLO', 'PYTHON']. index 0 to 3 (exclusive of 4):
Step 2 - Access the Second Word "MISS".
([1]): Step 2 - Extract S[-4:]:
S.split()[1] retrieves the second S[-4:] extracts the last 4
word: characters of the string:
"PYTHON". "IPPI".
Step 3 - Reverse the Word ([::-1]): Step 3 - Concatenate with '-':
"PYTHON"[::-1] reverses the Combine the results:
characters: "MISS" + '-' + "IPPI" → "MISS-IPPI"
"NOHTYP".
FINAL OUTPUT:
FINAL OUTPUT: MISS-IPPI
NOHTYP
KEY POINTS TO REMEMBER:
KEY POINTS TO REMEMBER: String slicing:
String splitting: The split() function S[start:end] extracts characters
creates a list of substrings. starting at start and stopping
Indexing: [1] accesses the second before end.
word of the list. S[-n:] extracts the last n
Reversing: [::-1] reverses the characters.
characters in a string. Concatenation: Use + to join strings
with custom characters like '-'.
QUESTION 9:
S = "MISSISSIPPI" Question 10:
print(S[0:4] + '-' + S[-4:]) lst = [100, 200, 300, 400]
print(lst[1::2])
Answer: (a) MISS-IPPI
Answer: (a) [200, 400]
CONCEPT INVOLVED:
String Slicing: CONCEPT INVOLVED:
S[start:end] extracts characters List Slicing:
from start (inclusive) to end The slicing syntax
(exclusive). lst[start::step] extracts
S[-n:] extracts the last n elements from the list starting
characters of the string. at start, skipping step elements
between selections.
CONCEPT INVOLVED:
If the step is 2, every second
List Slicing with Negative Indices
element is selected from the
and Steps:
starting index.
lst[start:end:step] allows slicing
with negative indices and steps.
STEP-BY-STEP EVALUATION:
Negative step means slicing
Expression:
proceeds in reverse order.
lst[1::2]
Default values:
Step 1 - Starting Index (1):
If end is omitted with a
The slicing starts at index 1.
negative step, slicing stops
lst[1] = 200.
at the start of the list.
Step 2 - Step Size (2):
From the starting index (1), every
STEP-BY-STEP EVALUATION:
second element is selected:
Expression:
First selection: lst[1] = 200
lst[-1::-3]
Second selection: lst[3] =
Step 1 - Starting Index (-1):
400
The index -1 refers to the last
Result:
element of the list: 'D'.
The sliced list is [200, 400].
Step 2 - End Condition (None):
No specific end is provided, so
FINAL OUTPUT:
slicing continues until the start
[200, 400]
of the list.
Step 3 - Step Size (-3):
KEY POINTS TO REMEMBER:
Moving backwards in steps of 3:
List slicing syntax:
Start at lst[-1] = 'D'
lst[start::step]:
Step back 3 indices to lst[-4]
start: The index to begin
= 'A'
slicing.
Result:
step: The number of
The sliced list is ['D', 'A'].
elements to skip.
Default values for slicing:
FINAL OUTPUT:
start=0 if omitted.
['D', 'A']
step=1 if omitted.
In this example, 1::2 starts at index 1
KEY POINTS TO REMEMBER:
and skips one element (step=2) in
Negative Step in Slicing:
each iteration.
A negative step reverses the
direction of slicing.
If end is not specified, slicing
continues to the start of the list.
QUESTION 11:
Negative Indices:
lst = ['A', 'B', 'C', 'D']
-1 refers to the last element of
print(lst[-1::-3])
the list.
Counting moves backwards: -1,
Answer: (b) ['D', 'A']
-2, -3, etc.
QUESTION 12: QUESTION 13:
L1 = [10, 20, 30] x = 50
print(L1.pop(), L1.pop(), L1.pop()) def modify():
x = 25
Answer: (b) 30, 20, 10 modify()
print(x)
CONCEPT INVOLVED:
pop() Method: Answer: (a) 50
Removes and returns the last
CONCEPT INVOLVED:
element of a list by default.
Variable Scope:
After a pop() operation, the list
Variables defined outside a
shrinks, and subsequent pop()
function are global variables.
calls operate on the updated
Variables defined inside a
list. function are local to that
If a list is empty, calling pop() function.
raises an IndexError. Local variables do not affect
global variables unless explicitly
STEP-BY-STEP EVALUATION: declared as global.
Initial List:
L1 = [10, 20, 30] STEP-BY-STEP EVALUATION:
Step 1 - First pop(): Initial Assignment:
L1.pop() removes and returns x = 50 creates a global variable x
the last element: 30. with the value 50.
Updated list: L1 = [10, 20]. Step 1 - Function modify():
Step 2 - Second pop(): Inside the function, a new local
L1.pop() removes and returns variable x is created with the
the last element: 20. value 25.
Updated list: L1 = [10]. This local x exists only within the
Step 3 - Third pop(): function and does not affect the
global x.
L1.pop() removes and returns
Step 2 - Call modify():
the last element: 10.
The function executes, but since
Updated list: L1 = [] (now empty).
the local x is not returned or
Result:
used outside the function, it has
The output is 30, 20, 10.
no impact on the global x.
Step 3 - Print x:
FINAL OUTPUT: The global x remains unchanged
30, 20, 10 at 50.
KEY POINTS TO REMEMBER: FINAL OUTPUT:
The pop() method removes the last 50
element of the list by default.
Each pop() operation modifies the KEY POINTS TO REMEMBER:
list in-place.Calling pop() on an Local variables defined inside a
empty list results in an IndexError. function are not accessible outside
the function.
To modify a global variable inside a
function, you must explicitly declare x=5
it with the global keyword: y=6
def modify(): Print the Values:
global x print(x, y) outputs 5, 6.
x = 25
In this case, the global x would be FINAL OUTPUT:
updated to 25. 5, 6
KEY POINTS TO REMEMBER:
Functions can return multiple
QUESTION 14:
values as a tuple, e.g., return a, b.
def calc(a, b):
These values can be unpacked into
return a + b, a * b
separate variables:
x, y = calc(2, 3)
x, y = calc(2, 3)
print(x, y)
Printing multiple variables with
print() separates them with a
Answer: (a) 5, 6
comma.
CONCEPT INVOLVED:
Multiple Return Values:
QUESTION 15:
In Python, a function can return
f = open("test.txt", "w")
multiple values as a tuple.
f.write("Hello\nPython")
These values can be unpacked
f.close()
into separate variables when the
function is called.
f = open("test.txt", "r")
print(f.readline().strip())
STEP-BY-STEP EVALUATION:
f.close()
Define the Function:
calc(a, b) takes two arguments a
Answer: (a) Hello
and b.
It returns two values:
CONCEPT INVOLVED:
The sum (a + b)
File Handling in Python:
The product (a * b)
open():
These values are returned as a
"w" mode: Opens a file for
tuple: (a + b, a * b).
writing, overwriting any
Call the Function:
existing content.
calc(2, 3) is called with
"r" mode: Opens a file for
arguments 2 and 3.
reading.
The function evaluates:
write():
a+b=2+3=5
Writes text to the file. In this
a*b=2*3=6
case, "Hello\nPython" is
Returns the tuple: (5, 6).
written, with a newline (\n)
Unpack the Return Values:
between "Hello" and
The tuple (5, 6) is unpacked into
"Python".
variables x and y:
readline(): QUESTION 16:
Reads a single line from the file. with open("data.txt", "w") as f:
strip(): f.writelines(["Line1\n", "Line2\n",
Removes any leading/trailing "Line3\n"])
whitespace, including the
newline character (\n). with open("data.txt", "r") as f:
for line in f.readlines():
STEP-BY-STEP EVALUATION: print(line.strip())
File Writing (w Mode):
The file test.txt is opened in Answer: (a) Line1 Line2 Line3
write mode ("w") and the string
"Hello\nPython" is written. CONCEPT INVOLVED:
The file now contains: File Handling with with Statement:
Hello The with statement ensures that
Python the file is properly closed after
File Reading (r Mode): the block is executed.
The file test.txt is reopened in writelines(): Writes a list of
read mode ("r"). strings to the file. Each string is
f.readline() reads the first line: written exactly as provided,
"Hello\n". including newline characters
strip() Method: (\n).
The strip() method removes the readlines(): Reads all lines of the
newline character (\n), leaving: file into a list, where each
"Hello" element corresponds to a line
Print Statement: including the newline character.
print(f.readline().strip()) outputs strip(): Removes leading and
the cleaned string: "Hello". trailing whitespaces (including
\n).
FINAL OUTPUT:
Hello STEP-BY-STEP EVALUATION:
File Writing (w Mode):
KEY POINTS TO REMEMBER: The file data.txt is opened in
write(): write mode ("w").
Writes the given string to the The writelines() method writes
file. Newline characters (\n) the following strings to the file:
create separate lines in the file. Line1\n
readline(): Line2\n
Reads one line at a time, Line3\n
including the newline character The file content after this step:
at the end (if present). Line1
strip(): Line2
Removes leading and trailing Line3
whitespaces, including \n.
File Reading (r Mode): QUESTION 17:
The file data.txt is reopened in def add(a, b):
read mode ("r"). return a + b
f.readlines() reads all lines into a
list: result = add(5, 10)
['Line1\n', 'Line2\n', 'Line3\n'] print(result)
Iteration and strip():
The for loop iterates through the Answer: (a) 15
list of lines:
First iteration: CONCEPT INVOLVED:
"Line1\n".strip() → "Line1" Function Definition and Return Value:
Second iteration: The add(a, b) function takes two
"Line2\n".strip() → "Line2" arguments, a and b, and returns
Third iteration: their sum.
"Line3\n".strip() → "Line3" a + b performs arithmetic addition
Print Statement: as both arguments are integers.
Each cleaned line is printed on a
new line: STEP-BY-STEP EVALUATION:
Line1 Function Definition:
Line2 The function add(a, b) is defined
Line3 to compute the sum of its two
parameters and return the result.
FINAL OUTPUT: Function Call:
Line1 add(5, 10) is called with
Line2 arguments 5 and 10.
Line3 Inside the function:
This matches option (a) when the a = 5, b = 10
lines are visually interpreted as a + b = 5 + 10 = 15
separate outputs. The function returns 15.
Assignment to result:
KEY POINTS TO REMEMBER: The returned value 15 is stored in
writelines(): the variable result.
Writes a list of strings to the file Print Statement:
without automatically print(result) outputs the value of
appending \n. result, which is 15.
Newline characters must be
explicitly included if required. FINAL OUTPUT:
readlines(): 15
Reads all lines into a list, where
each line retains its original KEY POINTS TO REMEMBER:
newline character. Arithmetic Addition (+):
strip(): When both operands are integers,
Removes trailing newlines and the + operator performs numeric
spaces for clean output. addition.
Third Call:
Function Return: recurse(1):
The return statement exits the n = 1, so the else block
function and provides a value to executes:
the caller. return 1 + recurse(0)
Variables and Scope: Base Case:
The variable result stores the recurse(0):
value returned by the function. n = 0, so the if block executes:
return 0
Returning Values:
QUESTION 18: recurse(1) returns:
def recurse(n): 1+0=1
if n == 0: recurse(2) returns:
return 0 2+1=3
else: recurse(3) returns:
return n + recurse(n-1) 3+3=6
print(recurse(3)) FINAL OUTPUT:
6
Answer: (b) 6
KEY POINTS TO REMEMBER:
CONCEPT INVOLVED: Recursion:
Recursion: Always include a base case (if n ==
A function that calls itself to solve 0 in this case) to avoid infinite
smaller subproblems. recursion.
Each recursive call reduces the The recursion builds a chain of calls,
problem size until a base case is which are resolved in reverse order.
reached. This example calculates the sum of
Base Case: numbers from n to 1, which is
if n == 0: return 0 ensures that the equivalent to the formula for the sum
recursion stops when n becomes of the first n natural numbers:
0. Sum = n * (n + 1) / 2
STEP-BY-STEP EVALUATION: QUESTION 19:
Initial Call: multiply = lambda x, y: x * y
recurse(3): print(multiply(4, 5))
n = 3, so the else block
executes: Answer: (a) 20
return 3 + recurse(2)
Second Call: CONCEPT INVOLVED:
recurse(2): Lambda Functions:
n = 2, so the else block A lambda function is an
executes: anonymous function defined using
return 2 + recurse(1) the lambda keyword.
QUESTION 20:
numbers = [1, 2, 3, 4]
Syntax: lambda arguments: squares = [x**2 for x in numbers]
expression. print(squares)
The expression is evaluated and
returned when the lambda Answer: (a) [1, 4, 9, 16]
function is called.
Arithmetic Operations: CONCEPT INVOLVED:
x * y performs multiplication when List Comprehension:
A concise way to create a new list
x and y are numbers.
by applying an operation to each
element of an existing list.
STEP-BY-STEP EVALUATION:
Syntax:
Lambda Function Definition:
[expression for item in iterable]
multiply = lambda x, y: x * y
Exponentiation (**):
creates a lambda function that The ** operator raises a number to
takes two arguments (x and y) and the power of another.
returns their product.
Function Call: STEP-BY-STEP EVALUATION:
multiply(4, 5): Original List:
x = 4, y = 5 numbers = [1, 2, 3, 4].
The lambda function List Comprehension:
evaluates: [x**2 for x in numbers] iterates over
4 * 5 = 20 each element x in numbers and
Print Statement: computes its square (x**2):
print(multiply(4, 5)) outputs the For x = 1: 1**2 = 1
result of the multiplication, which For x = 2: 2**2 = 4
is 20. For x = 3: 3**2 = 9
For x = 4: 4**2 = 16
FINAL OUTPUT: Resulting List:
20 The new list squares becomes:
[1, 4, 9, 16]
Print Statement:
KEY POINTS TO REMEMBER:
print(squares) outputs:
Lambda Functions:
[1, 4, 9, 16]
Useful for short, simple functions
that don’t require a formal def
FINAL OUTPUT:
structure. [1, 4, 9, 16]
Automatically return the result of
the expression; no need for an KEY POINTS TO REMEMBER:
explicit return statement. List Comprehension:
Multiplication (*): Simplifies operations on lists by
The * operator multiplies two applying an expression to each
numbers. element of an iterable.
Exponentiation:
x**2 computes the square of x.
QUESTION 21: QUESTION 22:
D = {'a': 1, 'b': 2, 'c': 3} try:
print(D.get('b'), D.get('d', 4)) print(10 / 0)
except ZeroDivisionError:
Answer: (a) 2 4 print("Cannot divide by zero")
finally:
CONCEPT INVOLVED: print("Execution Complete")
dict.get() Method:
Retrieves the value associated with Answer: (b) Cannot divide by zero
a specified key in a dictionary. followed by Execution Complete
Syntax: dict.get(key, default_value):
If key exists, it returns the CONCEPT INVOLVED:
corresponding value. Exception Handling (try, except,
If key does not exist, it returns finally):
the default_value (if provided); try Block:
otherwise, it returns None. Executes the code inside it.
If an exception occurs, the
STEP-BY-STEP EVALUATION: program immediately jumps to
Dictionary Initialization: the corresponding except block.
D = {'a': 1, 'b': 2, 'c': 3}. except Block:
First Call - D.get('b'): Handles a specific exception
'b' is a key in D, with the value 2. (e.g., ZeroDivisionError).
Returns: 2. finally Block:
Second Call - D.get('d', 4): Executes after the try or except
'd' is not a key in D. block, regardless of whether an
Since a default value (4) is exception occurred.
provided, it returns 4.
Print Statement: STEP-BY-STEP EVALUATION:
print(D.get('b'), D.get('d', 4)) try Block:
outputs: Executes the statement print(10 /
24 0).
Since dividing by zero raises a
FINAL OUTPUT: ZeroDivisionError, the program
24 jumps to the except block.
except Block:
KEY POINTS TO REMEMBER: Executes the statement:
get() Method: print("Cannot divide by zero")
If the key exists, it returns the Output so far:
corresponding value. Cannot divide by zero
If the key does not exist: finally Block:
Returns the default_value if Executes the statement:
specified. print("Execution Complete")
Returns None if no Appends to the output:
default_value is provided. Cannot divide by zero
This method avoids raising a KeyError Execution Complete
for missing keys, unlike direct access
(D['key']).
FINAL OUTPUT:
Cannot divide by zero Resulting String:
Execution Complete The evaluated f-string becomes:
"Alice is 21 years old."
KEY POINTS TO REMEMBER: Print Statement:
try-except: print() outputs the resulting string.
The except block catches and
handles specific exceptions to FINAL OUTPUT:
prevent program crashes. Alice is 21 years old.
finally:
Always executes, even if an KEY POINTS TO REMEMBER:
exception occurs in the try block or F-Strings:
no exceptions are raised. Use f before the string to enable
Order of Execution: embedded expressions.
try → except (if an exception occurs) Variables and expressions inside {}
→ finally. are evaluated at runtime.
F-strings are a concise and efficient
alternative to older string formatting
QUESTION 23: methods like str.format() or %.
name = "Alice"
age = 21
print(f"{name} is {age} years old.")
Answer: (a) Alice is 21 years old. QUESTION 24:
coordinates = (10, 20)
CONCEPT INVOLVED: x, y = coordinates
F-Strings (Formatted String Literals): print(x, y)
Introduced in Python 3.6, f-strings
allow you to embed expressions Answer: (a) 10 20
directly in string literals by
prefixing the string with f. CONCEPT INVOLVED:
Syntax: Tuple Unpacking:
f"text {expression} text" A tuple can be unpacked by
The expression inside {} is assigning its elements to variables
evaluated, and the result is inserted in a single statement.
into the string. Syntax:
x, y = (value1, value2)
STEP-BY-STEP EVALUATION: Each variable (x, y) is assigned a
Variable Assignments: corresponding element of the
name = "Alice" assigns the string tuple.
"Alice" to the variable name.
age = 21 assigns the integer 21 to STEP-BY-STEP EVALUATION:
the variable age. Tuple Definition:
F-String Expression: coordinates = (10, 20) creates a
The string inside f"{name} is {age} tuple with two elements:
years old." is evaluated: (10, 20)
{name} is replaced with "Alice".
{age} is replaced with 21.
Tuple Unpacking: STEP-BY-STEP EVALUATION:
x, y = coordinates unpacks the Set Definitions:
tuple: A = {1, 2, 3}
x is assigned the first element: B = {2, 3, 4}
10. Union of Sets (A.union(B)):
y is assigned the second Combines all unique elements
element: 20. from A and B:
Print Statement: {1, 2, 3} ∪ {2, 3, 4} = {1, 2, 3, 4}
print(x, y) outputs the values of x Intersection of Sets
and y, separated by a space: (A.intersection(B)):
10 20 Retrieves elements common to A
and B:
FINAL OUTPUT: {1, 2, 3} ∩ {2, 3, 4} = {2, 3}
10 20 Print Statement:
print(A.union(B), A.intersection(B))
KEY POINTS TO REMEMBER: outputs:
Tuple Unpacking: {1, 2, 3, 4} {2, 3}
The number of variables on the left
must match the number of FINAL OUTPUT:
elements in the tuple. {1, 2, 3, 4} {2, 3}
Each variable is assigned the value
of the corresponding element in KEY POINTS TO REMEMBER:
the tuple. union():
This is a concise and readable way to Includes all elements from both
extract values from a tuple. sets, without duplicates.
intersection():
Includes only elements present in
QUESTION 25: both sets.
A = {1, 2, 3} Set operations are order-
B = {2, 3, 4} independent.
print(A.union(B), A.intersection(B))
Answer: (a) {1, 2, 3, 4} {2, 3} QUESTION 26:
with open("test.txt", "w") as f:
CONCEPT INVOLVED: f.write("Hello\nWorld")
Set Operations: with open("test.txt", "r") as f:
union(): content = f.read()
Combines all unique elements print(content)
from both sets.
Syntax: A.union(B) or A | B. Answer: (c) Hello followed by World
intersection(): on a new line
Retrieves elements common to
both sets. Concept Involved:
Syntax: A.intersection(B) or A & File Handling in Python:
B. open() function: Opens a file and
returns a file object.
write() method: Writes a string to QUESTION 27:
the file. def outer():
read() method: Reads the contents def inner():
of the file. return "Inner"
Mode 'w' and 'r': return inner()
'w' mode opens the file for writing print(outer())
and creates the file if it doesn't
exist. It overwrites the content if Answer: (b) Inner
the file exists.
'r' mode opens the file for reading. CONCEPT INVOLVED:
Nested Functions:
STEP-BY-STEP EVALUATION: A function defined inside another
Opening the file in write mode ('w'): function is called a nested
with open("test.txt", "w") as f: function (or inner function).
The file test.txt is opened in write The inner function can be called
mode. If the file already exists, it is and executed within the outer
overwritten. function.
f.write("Hello\nWorld"): This writes Function Calls:
the string "Hello\nWorld" into the Return Statement: The return
file, including a newline (\n) statement in the outer function
character between "Hello" and returns the result of calling the
"World". inner function.
Opening the file in read mode ('r'): The inner() function is executed
with open("test.txt", "r") as f: when outer() is called.
The file test.txt is opened in read
mode. STEP-BY-STEP EVALUATION:
content = f.read(): This reads the Defining the outer function:
entire content of the file and def outer():
stores it in the variable content. This defines the outer function.
Printing the content: Defining the inner function inside the
print(content) outputs: outer function:
def inner(): return "Inner"
Hello The inner function returns the
World string "Inner" when called.
Calling the inner function from within
FINAL OUTPUT: the outer function:
Hello return inner(): This calls the inner
World function and returns its result
("Inner") as the result of the outer
KEY POINTS TO REMEMBER: function.
write() method writes text to a file. Printing the result of outer():
read() method reads the entire print(outer()): Since the outer
content of the file. function returns "Inner", the
The newline character (\n) in the print() statement outputs "Inner".
string separates the two words onto
different lines. FINAL OUTPUT:
Inner
KEY POINTS TO REMEMBER:
A nested function can be called and Recursive Call 2: factorial(2) is called.
executed inside the outer function. Since n=2, the function proceeds
The outer function can return the to the else block.
result of the inner function's The function returns 2 *
execution. factorial(1).
The return value of outer() is the Base Case Call: factorial(1) is called.
return value of inner(). Since n=1, the function returns 1.
Unwinding the recursion:
QUESTION 28: factorial(2) returns 2 * 1 = 2.
def factorial(n): factorial(3) returns 3 * 2 = 6.
if n == 1: factorial(4) returns 4 * 6 = 24.
return 1
else: FINAL OUTPUT:
return n * factorial(n-1) 24
print(factorial(4))
KEY POINTS TO REMEMBER:
Answer: 24 A recursive function must have a base
case to prevent infinite recursion.
CONCEPT INVOLVED: The factorial function multiplies the
Recursion: current number by the factorial of the
A recursive function is a function previous number, eventually reducing
that calls itself. to the base case.
In this case, the factorial()
function calls itself with a
decremented value of n.
Factorial Function:
The factorial of a number nnn
(denoted n!) is the product of all
positive integers less than or
equal to nnn.
The base case is when n=1, where
the function returns 1.
For any n>1, the function returns
n×factorial(n−1).
STEP-BY-STEP EVALUATION:
Initial Call: factorial(4) is called.
Since n=4, the function proceeds
to the else block.
The function returns 4 *
factorial(3).
Recursive Call 1: factorial(3) is called.
Since n=3, the function proceeds
to the else block.
The function returns 3 *
factorial(2).
QUESTION 29: Answer: (d) Struct
lst = [1, 2, 3]
lst.append([4, 5]) CONCEPT INVOLVED:
print(lst) String Slicing:
Python allows slicing of strings
Answer: (b) [1, 2, 3, [4, 5]] using the format s[start:end].
The slice starts at the start index
CONCEPT INVOLVED: and goes up to, but does not
List Method append(): include, the end index.
The append() method adds an Indexing:
element to the end of the list. The index of a string starts from 0.
If the element passed to append() For example:
is a list, it adds the entire list as a s[0] is 'D'
single element at the end. s[1] is 'a'
List Data Structure: s[2] is 't'
Lists can hold different types of s[3] is 'a'
elements, including other lists. s[4] is 'S'
And so on...
STEP-BY-STEP EVALUATION:
Initial List: STEP-BY-STEP EVALUATION:
lst = [1, 2, 3]: The list lst contains String Initialization:
the elements [1, 2, 3]. s = "DataStructures": The string s is
Using append() Method: initialized with the value
lst.append([4, 5]): The list [4, 5] is "DataStructures".
appended as a single element to Slicing the String:
lst. The entire list [4, 5] is treated s[4:10]: This extracts a substring
as one item, so the final list starting at index 4 and ending at
becomes [1, 2, 3, [4, 5]]. index 9 (since the end index is
Printing the List: exclusive).
print(lst) outputs: The substring from s[4] to s[9] is
[1, 2, 3, [4, 5]] "Struct".
Printing the Result:
FINAL OUTPUT: print(s[4:10]) will output "Struct".
[1, 2, 3, [4, 5]]
FINAL OUTPUT:
KEY POINTS TO REMEMBER: Struct
append() adds an element to the list
as a single item, even if that item is KEY POINTS TO REMEMBER:
itself a list. String slicing in Python follows the
The list inside lst is nested as a sublist. format s[start:end], where the
substring includes start but excludes
end.
QUESTION 30: The indices are 0-based, and the
s = "DataStructures" slicing does not include the character
print(s[4:10]) at the end index.
QUESTION 31:
a = True
b = False QUESTION 32:
print(a and b, a or b, not a, not b) lst = ['Python', 'Java', 'C++']
print(lst[2], lst[-1])
Answer: (a) False True False True
Answer: (a) C++ C++
CONCEPT INVOLVED:
Logical Operators:
CONCEPT INVOLVED:
and: Returns True if both
List Indexing:
operands are True, otherwise
returns False. Lists in Python are indexed
or: Returns True if at least one starting from 0.
operand is True, otherwise returns Positive indices start from 0 and
False. go forward, while negative indices
not: Returns the opposite of the start from -1 and go backward.
boolean value. Accessing Elements:
Boolean Values: lst[2]: Accesses the element at
True represents a truthy value. index 2 (third element) in the list,
False represents a falsy value. which is 'C++'.
STEP-BY-STEP EVALUATION: lst[-1]: Accesses the last element
a and b: of the list, which is also 'C++'.
a = True, b = False
True and False evaluates to False STEP-BY-STEP EVALUATION:
because both operands must be True Indexing lst[2]:
for the result to be True. The list lst is ['Python', 'Java',
a or b:
'C++'].
a = True, b = False
lst[2] refers to the element at
True or False evaluates to True
because at least one operand is True. index 2, which is 'C++'.
not a: Indexing lst[-1]:
a = True lst[-1] refers to the last element of
not True evaluates to False. the list, which is also 'C++'.
not b: Printing the Values:
b = False print(lst[2], lst[-1]) prints both
not False evaluates to True. 'C++' and 'C++'.
FINAL OUTPUT:
FINAL OUTPUT:
The output of print(a and b, a or b, not
C++ C++
a, not b) is:
False True False True
KEY POINTS TO REMEMBER:
KEY POINTS TO REMEMBER: Positive indices start from 0 and go
and requires both operands to be forward in the list.
True for the result to be True. Negative indices start from -1 (last
or requires at least one operand to be element) and go backward.
True for the result to be True. Both lst[2] and lst[-1] refer to the
not negates the boolean value of the same element 'C++' in this case.
operand.
QUESTION 33: QUESTION 34:
s = "hello world" def func(a, b=5):
print(s.capitalize(), s.upper()) return a + b
Answer: (a) Hello world HELLO print(func(3))
WORLD
Answer: (a) 8
CONCEPT INVOLVED:
String Method capitalize(): CONCEPT INVOLVED:
The capitalize() method converts Function Parameters:
the first character of a string to The function func takes two
uppercase and the rest of the parameters: a and b.
characters to lowercase. b has a default value of 5. This
Example: "hello".capitalize() means if b is not provided when
returns "Hello". calling the function, it will default
String Method upper(): to 5.
The upper() method converts all Function Call:
characters in the string to When func(3) is called, the value 3
uppercase. is passed to a, and since no value
Example: "hello".upper() returns is provided for b, it takes the
"HELLO". default value of 5.
Return Statement:
STEP-BY-STEP EVALUATION: The function returns a + b. With a =
Using capitalize() on s: 3 and b = 5, the result is 3 + 5 = 8.
s = "hello world".
s.capitalize() changes the first STEP-BY-STEP EVALUATION:
letter to uppercase and the rest to Calling the function:
lowercase: "Hello world". func(3) passes a = 3 and uses the
Using upper() on s: default value b = 5.
s = "hello world". Return Value:
s.upper() changes all letters to The return value is 3 + 5 = 8.
uppercase: "HELLO WORLD". Printing the Result:
Printing the Values: print(func(3)) prints 8.
print(s.capitalize(), s.upper())
prints: FINAL OUTPUT:
Hello world HELLO WORLD 8
FINAL OUTPUT: KEY POINTS TO REMEMBER:
Hello world HELLO WORLD Default parameters are used if no
value is provided for them when
KEY POINTS TO REMEMBER: calling the function.
capitalize(): Only the first letter is The function's return value is
capitalized, and the rest are in calculated based on the parameters
lowercase. provided or their default values.
upper(): Converts the entire string to
uppercase.
FINAL OUTPUT:
QUESTION 35:
def func(n): Error (RecursionError: maximum
if n == 0: recursion depth exceeded in
return 0 comparison)
else:
return n + func(n-2) KEY POINTS TO REMEMBER:
print(func(5)) Recursion should have a well-defined
base case to stop the recursion.
Answer: (d) Error Without handling negative values
properly in this case, the function
CONCEPT INVOLVED: leads to infinite recursion, causing a
Recursion: RecursionError.
Recursion is a process where a
function calls itself to solve a
smaller instance of the problem. QUESTION 36:
The base case is used to stop the keys = ['a', 'b', 'c']
recursion. In this case, the values = [1, 2, 3]
function stops when n == 0. D = {k: v for k, v in zip(keys, values)}
Infinite Recursion: print(D)
If the base case is not met, the
function will continue calling itself Answer: (a) {'a': 1, 'b': 2, 'c': 3}
indefinitely.
In this code, the function calls CONCEPT INVOLVED:
func(n-2), but there's no check for zip() Function:
negative values, so the recursion
Combines two iterables into pairs
never stops when n becomes
of tuples.
negative.
Example: zip(['a', 'b'], [1, 2])
produces [('a', 1), ('b', 2)].
STEP-BY-STEP EVALUATION:
First Call (func(5)): Dictionary Comprehension:
n = 5, not equal to 0, so it returns 5 A concise way to construct a
+ func(3). dictionary.
Second Call (func(3)): Syntax: {key: value for key, value in
n = 3, not equal to 0, so it returns 3 iterable}.
+ func(1). Example: {k: v for k, v in [('a', 1), ('b',
Third Call (func(1)): 2)]} results in {'a': 1, 'b': 2}.
n = 1, not equal to 0, so it returns 1
+ func(-1). STEP-BY-STEP EVALUATION:
Subsequent Calls (func(-1), func(-3), Input Lists:
func(-5), etc.): keys = ['a', 'b', 'c']
The recursion continues values = [1, 2, 3]
indefinitely with decreasing values Using zip():
of n, never reaching the base case zip(keys, values) produces:
n == 0. [('a', 1), ('b', 2), ('c', 3)]
Result: Dictionary Comprehension:
Eventually, Python raises a
{k: v for k, v in zip(keys, values)}
RecursionError due to exceeding
creates the dictionary:
the recursion depth limit.
{'a': 1, 'b': 2, 'c': 3}
Print Statement: Print Statement:
print(D) outputs: print(matrix[0][1], matrix[1][0])
{'a': 1, 'b': 2, 'c': 3} Outputs: 2 3
FINAL OUTPUT: FINAL OUTPUT:
{'A': 1, 'B': 2, 'C': 3} 23
KEY POINTS TO REMEMBER: KEY POINTS TO REMEMBER:
zip() pairs elements from two In a 2D list, the first index specifies
iterables. the row, and the second specifies the
Dictionary comprehension creates column.
dictionaries efficiently from iterables. Indexing starts from 0, so matrix[0][1]
The keys and values retain their types refers to the second element of the
as defined in the input lists. first row, and matrix[1][0] refers to
the first element of the second row.
QUESTION 37: QUESTION 38:
matrix = [[1, 2], [3, 4]] s = "banana"
print(matrix[0][1], matrix[1][0]) print(s.replace('a', 'o'))
Answer: (a) 2 3 Answer: (a) bonono
CONCEPT INVOLVED: CONCEPT INVOLVED:
Nested Lists (2D List): replace() Method:
A 2D list is a list of lists, where Used to replace all occurrences of
each inner list represents a row of a substring within a string with
the matrix. another substring.
Indexing is performed first for the Syntax: string.replace(old, new)
row and then for the column. Returns a new string where old is
Accessing Elements in a 2D List: replaced with new. The original string
Syntax: matrix[row_index] remains unchanged.
[column_index]
matrix[0][1] accesses the STEP-BY-STEP EVALUATION:
element at row 0, column 1. Define the String:
matrix[1][0] accesses the s = "banana"
element at row 1, column 0. Apply replace():
Replace all occurrences of 'a' with
Step-by-Step Evaluation: 'o':
Define the Matrix: "banana" -> "bonono"
matrix = [[1, 2], [3, 4]] Print Statement:
Row 0: [1, 2] print(s.replace('a', 'o'))
Row 1: [3, 4] Outputs: bonono
Access matrix[0][1]:
Row 0: [1, 2] FINAL OUTPUT:
Column 1 of Row 0: 2 bonono
Access matrix[1][0]:
Row 1: [3, 4] KEY POINTS TO REMEMBER:
Column 0 of Row 1: 3 replace() affects all occurrences of
the substring unless limited by an
optional count parameter.
Strings are immutable in Python, so
greet("Alice")
the original string remains unchanged
greet("Bob", "Hello")
after calling replace().
Answer: (a)
QUESTION 39: Good morning! Alice
A = {1, 2, 3} Hello Bob
B = {3, 4, 5}
print(A - B, B - A) CONCEPT INVOLVED:
Default Parameters in Functions:
Answer: (a) {1, 2} {4, 5} A default parameter is used when
no value is provided for the
CONCEPT INVOLVED: corresponding argument during a
Set Difference (-): function call.
The difference of two sets returns Syntax: def
the elements that are in the first func(arg=default_value):
set but not in the second. If an argument is passed explicitly,
Syntax: A - B gives elements in A it overrides the default value.
but not in B.
STEP-BY-STEP EVALUATION:
STEP-BY-STEP EVALUATION: Define the Function:
Define the Sets: def greet(name, msg="Good
A = {1, 2, 3} morning!"):
B = {3, 4, 5} print(msg, name)
Calculate A - B: The parameter msg has a default
Elements in A but not in B: value of "Good morning!".
{1, 2, 3} - {3, 4, 5} = {1, 2} Function Call greet("Alice"):
Calculate B - A: Only name is provided; msg uses
Elements in B but not in A: its default value "Good morning!".
{3, 4, 5} - {1, 2, 3} = {4, 5} Output:
Print Statement: Good morning! Alice
print(A - B, B - A) Function Call greet("Bob", "Hello"):
Outputs: {1, 2} {4, 5} Both name and msg are provided,
so the default value of msg is
FINAL OUTPUT: overridden with "Hello".
{1, 2} {4, 5} Output:
Hello Bob
KEY POINTS TO REMEMBER:
Set Difference (-): FINAL OUTPUT:
Non-commutative, meaning A - B Good morning! Alice
is not the same as B - A. Hello Bob
Returns elements present in the
first set but not in the second. KEY POINTS TO REMEMBER:
No error occurs as long as the Default parameter values are used
operands are valid sets. only when no value is explicitly
provided for that parameter.
QUESTION 40: Parameters provided explicitly during
def greet(name, msg="Good a function call override default
morning!"): values.
print(msg, name)
QUESTION 42:
QUESTION 41:
t = (1, 2, 3)
lst = [10, 20, 30, 40, 50, 60]
t += (4,)
print(lst[::2])
print(t)
Answer: (a) [10, 30, 50]
Answer: (a) (1, 2, 3, 4)
CONCEPT INVOLVED:
CONCEPT INVOLVED:
List Slicing:
Tuples in Python:
Syntax: lst[start:stop:step]
Tuples are immutable sequences,
start: Starting index (default is 0).
meaning their elements cannot be
stop: Ending index (default is the
changed after creation.
length of the list).
However, you can concatenate
step: Step size (default is 1).
tuples to create a new tuple.
A positive step skips elements in the
Syntax for a single-element tuple:
list by that step size.
(element,) (comma is required).
Tuple Concatenation (+=):
STEP-BY-STEP EVALUATION:
Concatenation creates a new tuple
Define the List:
with elements from both tuples
lst = [10, 20, 30, 40, 50, 60]
combined.
Slicing with lst[::2]:
The original tuple remains
start: Defaults to 0 (beginning of the
unchanged, but the new tuple is
list).
assigned to the variable.
stop: Defaults to the length of the
list (end of the list).
STEP-BY-STEP EVALUATION:
step: 2, meaning every second
Define the Tuple:
element is included.
t = (1, 2, 3)
Elements Included:
Concatenate Tuple (4,):
Index 0: 10
(4,) is a single-element tuple.
Index 2: 30
t += (4,) concatenates (1, 2, 3) and
Index 4: 50
(4,) to form a new tuple:
Resulting List:
(1, 2, 3) + (4,) = (1, 2, 3, 4)
[10, 30, 50]
Print Statement:
Print Statement:
print(t)
print(lst[::2])
Outputs: (1, 2, 3, 4)
Outputs: [10, 30, 50]
FINAL OUTPUT:
FINAL OUTPUT:
(1, 2, 3, 4)
[10, 30, 50]
KEY POINTS TO REMEMBER:
KEY POINTS TO REMEMBER:
Tuples are immutable, so elements
Slicing with a step:
cannot be modified directly.
Includes elements at indices start,
Concatenation creates a new tuple; the
start + step, start + 2*step, etc.
original remains unchanged.
If step is omitted or set to 1, all elements
A comma is necessary when creating
in the specified range are included.
single-element tuples.
A larger step skips more elements.
Arithmetic operations are valid on
QUESTION 43:
numeric dictionary values.
D = {'x': 10, 'y': 20}
print(D['x'] + D.get('y'))
QUESTION 44:
Answer: (a) 30 for i in range(3):
if i == 1:
CONCEPT INVOLVED: continue
Dictionary Basics: print(i, end=' ')
A dictionary is a collection of key-
value pairs, where keys are unique. Answer: (b) 0 2
Accessing values:
D['key']: Returns the value for CONCEPT INVOLVED:
the specified key; raises a for Loop:
KeyError if the key is not found. Iterates over a range of numbers, in
D.get('key'): Returns the value this case, range(3) generates 0, 1, 2.
for the specified key; returns continue Statement:
None (or a default value) if the Skips the rest of the loop body for
key is not found. the current iteration and proceeds
Arithmetic Operation on Values:
with the next iteration.
You can perform arithmetic
print with end:
operations on values retrieved
Prints output on the same line,
from a dictionary.
separated by a space (end=' ').
STEP-BY-STEP EVALUATION:
Define the Dictionary: STEP-BY-STEP EVALUATION:
D = {'x': 10, 'y': 20} Iteration 1 (i = 0):
Retrieve Values: if i == 1: False (condition is not met).
D['x'] retrieves the value for key 'x': print(0, end=' '): Outputs 0.
10. Iteration 2 (i = 1):
D.get('y') retrieves the value for key if i == 1: True (condition is met).
'y': 20. continue: Skips the print statement
Add Retrieved Values: for this iteration.
10 + 20 = 30 Iteration 3 (i = 2):
Print Statement: if i == 1: False (condition is not met).
print(D['x'] + D.get('y')) print(2, end=' '): Outputs 2.
Outputs: 30
FINAL OUTPUT:
FINAL OUTPUT: 02
30
KEY POINTS TO REMEMBER:
KEY POINTS TO REMEMBER:
The continue statement skips the
Use D['key'] when you're certain the
remaining loop body for the current
key exists; otherwise, it raises a
iteration.
KeyError.
Use D.get('key') to avoid errors when print(..., end=' ') ensures all output is
the key might not exist; it returns None printed on the same line, separated by
(or a specified default value) if the key spaces.
is absent. Use range(n) to generate numbers from
0 to n-1.
QUESTION 45: KEY POINTS TO REMEMBER:
def recursive_sum(n): Recursion is effective for problems
if n == 0: that can be broken into smaller
return 0 subproblems.
else: Always define a base case to avoid
return n + recursive_sum(n-1) infinite recursion.
The recursive calls are resolved in
print(recursive_sum(2)) reverse order (backtracking).
Answer: (a) 3 QUESTION 46:
s = "Data Science"
CONCEPT INVOLVED: print(s.split())
Recursion:
A function calls itself to solve Answer: (a) ['Data', 'Science']
smaller subproblems.
The recursion must have a base CONCEPT INVOLVED:
case to terminate the function. String Splitting:
Base Case: The split() method splits a string
if n == 0: return 0: Stops recursion into a list of substrings based on a
delimiter (default is whitespace).
when n reaches 0.
s.split() with no arguments splits the
Recursive Case:
string at every space and removes
return n + recursive_sum(n-1): Adds
extra whitespace.
the current value of n to the result
of recursive_sum(n-1). STEP-BY-STEP EVALUATION:
Define the String:
STEP-BY-STEP EVALUATION: s = "Data Science"
Initial Call: recursive_sum(2) Apply the split() Method:
n is 2, so it enters the else block: The string "Data Science" contains a
return 2 + recursive_sum(1) single space between the words.
Recursive Call 1: recursive_sum(1) s.split() splits the string at the
n is 1, so it enters the else block: space:
return 1 + recursive_sum(0) ['Data', 'Science']
Recursive Call 2: recursive_sum(0) Print Statement:
n is 0, so it enters the if block: print(s.split())
return 0 Outputs: ['Data', 'Science']
Backtracking Results:
recursive_sum(1) becomes: FINAL OUTPUT:
1+0=1 ['Data', 'Science']
recursive_sum(2) becomes:
KEY POINTS TO REMEMBER:
2+1=3
split() without arguments splits the
Print Statement:
string at whitespace.
print(recursive_sum(2))
The result of split() is always a list of
Outputs: 3
substrings.
Leading and trailing whitespace is
FINAL OUTPUT: ignored when using split() with the
3 default delimiter.
QUESTION 48:
QUESTION 47:
x=5
lst = [1, 2, 3]
def func():
lst[1] = lst[2] + lst[0]
x = 10
print(lst)
print(x)
func()
Answer: (a) [1, 4, 3]
print(x)
CONCEPT INVOLVED:
Answer: (a) 10 5
List Indexing:
In Python, lists are indexed starting
CONCEPT INVOLVED:
from 0.
Variable Scope:
lst[0] is the first element, lst[1] is
Variables defined inside a function
the second, and lst[2] is the third.
are local to that function.
Element Assignment:
Variables defined outside a function
Assigning a value to a list index
have a global scope and are not
updates the value at that position.
affected by changes to similarly
Arithmetic Operation:
named variables inside functions
lst[2] + lst[0] computes the sum of
unless explicitly modified using the
the third and first elements of the
global keyword.
list.
Local vs. Global:
Local variables are created when
STEP-BY-STEP EVALUATION:
the function is called and destroyed
Initial List:
when the function ends.
lst = [1, 2, 3]
Global variables persist throughout
Assignment Operation:
the program.
lst[1] = lst[2] + lst[0]
Evaluate lst[2] + lst[0]:
STEP-BY-STEP EVALUATION:
3+1=4
Global Variable Initialization:
Assign 4 to lst[1]:
x=5
lst = [1, 4, 3]
Function Definition:
Print Statement:
def func():
print(lst)
x = 10 # Local variable inside the
Outputs: [1, 4, 3]
function
print(x) # Prints the local `x` value: 10
FINAL OUTPUT:
Function Call:
[1, 4, 3]
func() is called:
Inside func(), x is set to 10
KEY POINTS TO REMEMBER:
(local).
Indexing in Python starts at 0.
print(x) outputs:
Assignment to a list index modifies the
10
list in place.
Global Scope Print:
Arithmetic operations on list elements
After the function call, print(x)
follow standard Python arithmetic
refers to the global x, which remains
rules.
unchanged (5):
5
FINAL OUTPUT: Step-by-Step Evaluation:
10 File Content:
5 Line1
Line2
KEY POINTS TO REMEMBER: Line3
Changes to local variables do not affect
global variables with the same name. Open File for Reading:
Use the global keyword if you need to with open("data.txt", "r") as f: opens
modify a global variable inside a the file safely for reading.
function. Iterate Through File Lines:
Local variables have a scope limited to Each line corresponds to one line in
the function in which they are defined. the file:
line.strip() removes the trailing
newline (\n) and any extra
QUESTION 49: spaces.
# Contents of "data.txt": Print Each Line:
# Line1 The print() function outputs each
# Line2 stripped line on a new line:
# Line3 Line1
with open("data.txt", "r") as f: Line2
for line in f: Line3
print(line.strip())
FINAL OUTPUT:
Answer: (a) Line1
Line1 Line2
Line2 Line3
Line3
KEY POINTS TO REMEMBER:
CONCEPT INVOLVED: Use the strip() method to clean
File Handling: whitespace and newline characters
The open() function is used to open when reading files.
files. The mode "r" specifies that the The with statement ensures proper file
file is opened for reading. handling and automatic closure.
Iteration Through File Lines: Iterating over a file object yields one
Using a for loop on a file object line at a time.
reads the file line by line.
String Method strip():
The strip() method removes leading QUESTION 50:
and trailing whitespace (including numbers = [1, 2, 3, 4, 5]
newline characters) from a string. even_squares = [x**2 for x in numbers if
Print Function: x % 2 == 0]
Each line is printed separately, print(even_squares)
preserving its structure after
stripping whitespace. Answer: (b) [4, 16]
Even Numbers Check:
result = x * y / z + x
x % 2 == 0 checks whether x is even
print(result)
(remainder is 0 when divided by 2).
Square Calculation: Answer: (b) 8.3333
x**2 computes the square of x.
CONCEPT INVOLVED:
STEP-BY-STEP EVALUATION: Operator Precedence:
Multiplication (*) and division (/)
Input List:
have higher precedence than
numbers = [1, 2, 3, 4, 5] addition (+).
List Comprehension: Operations of the same precedence
Iterate over each element x in (like * and /) are evaluated left to
numbers: right.
Floating-Point Arithmetic:
If x % 2 == 0 (even), calculate
Division results in a floating-point
x**2 and include it in the result number in Python.
list.
Steps: STEP-BY-STEP EVALUATION:
For x = 1: Not even → Excluded. Variable Assignment:
x=5
For x = 2: Even → 2**2 = 4.
y = 10
For x = 3: Not even → Excluded. z = 15
For x = 4: Even → 4**2 = 16. Expression Evaluation:
For x = 5: Not even → Excluded. x * y / z + x is evaluated as:
Result List: Compute x * y:
5 * 10 = 50
even_squares = [4, 16]
Compute 50 / z:
Print Statement: 50 / 15 = 3.3333...
Outputs: (approximately 3.3333 in
[4, 16] floating-point)
Add x to the result:
3.3333 + 5 = 8.3333
FINAL OUTPUT:
Final Value of result:
[4, 16] result = 8.3333
Print Statement:
KEY POINTS TO REMEMBER: Outputs:
List comprehensions combine filtering 8.3333
and transformation in a compact way.
FINAL OUTPUT:
Conditions in list comprehensions (if x 8.3333
% 2 == 0) filter items.
The x**2 expression applies a KEY POINTS TO REMEMBER:
transformation to each filtered item. Division in Python involving integers
produces a floating-point number.
Operator precedence determines the
order of operations.
QUESTION 51: Floating-point arithmetic may
x, y, z = 5, 10, 15 introduce minor rounding errors.
QUESTION 52: QUESTION 53:
S = "Information" S = "HELLO"
print(S[3:8] + S[-3:]) print(S[-3], S[2])
Answer: (b) ormation Answer: (a) L L
CONCEPT INVOLVED: CONCEPT INVOLVED:
String Slicing: String Indexing:
Slicing extracts a portion of a string. Strings in Python are indexed
starting from 0 for the first
S[start:end] gives characters from
character.
index start to end-1.
Negative indexing starts from the
Negative Indexing:
end of the string, with -1 referring to
Negative indices count from the
the last character.
end of the string. For example, S[-1]
Accessing Individual Characters:
refers to the last character. S[index] retrieves the character at
the specified index.
STEP-BY-STEP EVALUATION:
S[3:8]: STEP-BY-STEP EVALUATION:
This extracts characters starting S[-3]:
from index 3 up to index 7 (8 is not The negative index -3 refers to the
included). 3rd character from the end.
S[3:8] results in "ormat". In "HELLO", the 3rd character from
S[-3:]: the end is "L".
S[-3:] starts from the 3rd character S[2]:
from the end and goes to the end of The positive index 2 refers to the
the string. 3rd character from the start (0-
S[-3:] results in "ion". based indexing).
Concatenation: In "HELLO", the character at index 2
The concatenation of "ormat" and is also "L".
"ion" gives "ormation". Output:
The output of the print statement is
"L L", with a space separating the
FINAL OUTPUT:
two characters.
ormation
FINAL OUTPUT:
KEY POINTS TO REMEMBER:
LL
String slicing with positive indices
(S[start:end]) extracts from start to KEY POINTS TO REMEMBER:
end-1. Positive indexing (S[n]) starts from 0
String slicing with negative indices (S[- and moves forward.
n:]) starts from the nth character from Negative indexing (S[-n]) starts from -1
the end to the end of the string. and moves backward.
Concatenation combines strings Characters retrieved with indexing are
together. separated by a space in the print()
function if multiple values are printed.
QUESTION 54: QUESTION 55:
for i in range(1, 3): lst = [1, 3, 5, 7]
for j in range(i, 4): lst.insert(2, 9)
print(i * j, end=" ") print(lst)
Answer: (b) 1 2 3 4 6 Answer: (a) [1, 3, 9, 5, 7]
CONCEPT INVOLVED: CONCEPT INVOLVED:
Nested Loops: List Indexing:
The outer for loop iterates over i Lists in Python are zero-indexed,
from 1 to 2 (range(1, 3) excludes 3). meaning the first element is at
The inner for loop iterates over j index 0.
from i to 3 (range(i, 4) excludes 4). insert() Method:
Range Function: Syntax: list.insert(index, element)
range(start, end) generates Inserts the element at the specified
numbers starting from start to end- index.
1. Existing elements are shifted one
Multiplication and Print: position to the right to make space
The expression i * j computes the for the new element.
product of the current values of i
and j. STEP-BY-STEP EVALUATION:
end=" " ensures the output is printed Initial List:
on the same line with spaces. lst = [1, 3, 5, 7]
lst.insert(2, 9):
STEP-BY-STEP EVALUATION: The method inserts 9 at index 2.
Outer Loop (i = 1): Elements 5 and 7 (and any
Inner Loop (j = 1 to 3): subsequent elements, if present)
i=1, j=1: 1 * 1 = 1 are shifted right.
i=1, j=2: 1 * 2 = 2 Result: [1, 3, 9, 5, 7]
i=1, j=3: 1 * 3 = 3 print(lst):
Outputs: 1 2 3 Prints the updated list.
Outer Loop (i = 2):
Inner Loop (j = 2 to 3): FINAL OUTPUT:
i=2, j=2: 2 * 2 = 4 [1, 3, 9, 5, 7]
i=2, j=3: 2 * 3 = 6
Outputs: 4 6 KEY POINTS TO REMEMBER:
Final Output: Index Position: insert(index, value)
Combining all results: 1 2 3 4 6 places value before the element
currently at index.
FINAL OUTPUT: Shifting Elements: Elements at and
12346 after the specified index are shifted to
the right.
KEY POINTS TO REMEMBER: Zero-Based Indexing: Python uses zero-
Nested Loops Execution: The inner loop based indexing for list operation
completes all iterations for each
iteration of the outer loop.
QUESTION 56:
Range Exclusion: range(start, end)
D = {'a': 1, 'b': 2, 'c': 3}
includes start but excludes end.
del D['b']
Output Formatting: end=" " ensures all
print(D)
values are printed on the same line,
separated by spaces.
Answer: (b) {'a': 1, 'c': 3}
CONCEPT INVOLVED: Variable Substitution:
Dictionaries in Python: The value of the variable or
A dictionary is a collection of key- expression inside {} is evaluated
value pairs. and inserted into the string.
Keys are unique and are used to
access the corresponding values. STEP-BY-STEP EVALUATION:
del Statement: Variable Declaration:
Syntax: del dictionary[key] x = 42
Deletes the key-value pair f-string:
associated with the specified key. f"The value of x is {x}."
Raises a KeyError if the key does not {x} is replaced with the value of the
exist in the dictionary. variable x, which is 42.
Output:
STEP-BY-STEP EVALUATION: The final string is "The value of x is
Initial Dictionary: 42.".
D = {'a': 1, 'b': 2, 'c': 3}
Delete Key 'b': FINAL OUTPUT:
del D['b'] removes the key-value The value of x is 42.
pair 'b': 2 from the dictionary.
The dictionary becomes: {'a': 1, 'c': KEY POINTS TO REMEMBER:
3}. f-strings Syntax: Use f before the string
Print the Updated Dictionary: and place expressions inside {}.
print(D) outputs {'a': 1, 'c': 3}. Dynamic Evaluation: The expressions
inside {} are evaluated at runtime.
FINAL OUTPUT: Readability: f-strings provide a cleaner
{'a': 1, 'c': 3} and more readable way to format
strings compared to older methods like
KEY POINTS TO REMEMBER: str.format() or concatenation.
Key Deletion: Use del to remove
specific key-value pairs from a
dictionary. QUESTION 58:
Error Handling: Deleting a non-existent text = "Python Programming"
key raises a KeyError. print(text.lower().replace("python",
Dictionary Mutability: Dictionaries are "Java"))
mutable, and their contents can be
modified after creation.
Answer: (a) Java programming
QUESTION 57: CONCEPT INVOLVED:
x = 42 String Methods:
print(f"The value of x is {x}.") lower(): Converts all characters in
the string to lowercase.
Answer: (a) The value of x is 42. replace(old, new): Replaces all
occurrences of the old substring
CONCEPT INVOLVED: with the new substring in the string.
f-strings (Formatted String Literals):
Chained Method Calls:
Introduced in Python 3.6.
Syntax: f"string {expression}" Methods can be called sequentially.
Allows embedding expressions (e.g., For example, text.lower().replace(...)
variables or calculations) directly first converts the string to
into strings. lowercase and then applies replace.
STEP-BY-STEP EVALUATION: Escape Sequences:
Initial String: \n: Represents a newline character,
text = "Python Programming" which moves the cursor to the next
text.lower(): line.
Converts "Python Programming" to File Operations:
"python programming".
write(string): Writes the string to the
.replace("python", "Java"):
Replaces "python" with "Java" in file.
"python programming". read(): Reads the entire content of the
Result: "Java programming" file as a single string.
Print the Result:
Outputs: "Java programming" STEP-BY-STEP EVALUATION:
Open File in Write Mode ("w"):
FINAL OUTPUT: f = open("sample.txt", "w"): Opens the
Java programming file sample.txt in write mode.
f.write("Hello\nWorld"): Writes the
KEY POINTS TO REMEMBER:
string "Hello\nWorld" to the file. The \n
Case Sensitivity: String methods like
replace are case-sensitive. "Python" introduces a newline.
and "python" are treated as different Close File:
strings. f.close(): Closes the file after writing.
Method Chaining: Methods like lower Open File in Read Mode ("r"):
and replace can be chained to perform f = open("sample.txt", "r"): Opens the
multiple operations in sequence. file sample.txt in read mode.
Immutability of Strings: Strings are Read Content:
immutable in Python. Operations like f.read(): Reads the file's content as a
lower and replace return a new string
single string: "Hello\nWorld".
without modifying the original.
When printed, the \n renders as a
newline.
QUESTION 59: Close File:
f = open("sample.txt", "w") f.close(): Closes the file after reading.
f.write("Hello\nWorld") Print Output:
f.close() Displays:
f = open("sample.txt", "r") Hello
print(f.read()) World
f.close()
FINAL OUTPUT:
Answer: (c) Hello followed by World on
Hello
a new line
World
CONCEPT INVOLVED:
File Handling: KEY POINTS TO REMEMBER:
open(filename, mode): Opens a file Escape Sequences: \n in a string
in the specified mode. Common represents a newline when printed.
modes: File Modes: Use "w" to write, "r" to read,
"w": Write mode, creates a new and always close files after operations.
file or overwrites an existing file. File Contents: Reading with read()
"r": Read mode, used to read the
returns the exact content, including
contents of a file.
any escape sequences.
QUESTION 60: Summation Pattern: Recursively adding
lst = [10, 20, 30, 40, 50] numbers down to 0 follows the
print(lst[1::2]) formula: sum=n+(n−1)+⋯+1+0
Debugging Recursion: Trace recursive
Answer: (a) [20, 40] calls step-by-step to understand the
flow.
CONCEPT INVOLVED:
List Slicing:
Syntax: list[start:stop:step] QUESTION 61:
start: The index to begin the tup = (1, 2, 3)
slice (inclusive). tup += (4,)
stop: The index to end the slice print(tup)
(exclusive).
step: The increment between Answer: (a) (1, 2, 3, 4)
indices.
If stop is omitted, the slice CONCEPT INVOLVED:
continues to the end of the list. Tuples in Python:
Default Parameters: Tuples are immutable sequences,
If start is omitted, slicing starts meaning their elements cannot be
from the beginning. modified after creation.
If step is omitted, it defaults to 1. However, tuples can be combined
(concatenated) to create a new
STEP-BY-STEP EVALUATION: tuple.
List Initialization: Tuple Concatenation:
lst = [10, 20, 30, 40, 50] Using the + operator with tuples
Slicing Operation: creates a new tuple that combines
lst[1::2]: the contents of both tuples.
start = 1: Starts slicing at index 1 Single-Element Tuples:
(value: 20). To create a single-element tuple,
step = 2: Selects every second include a trailing comma: (4,).
element from index 1. Without the comma, (4) is treated as
Result: [20, 40] an integer in parentheses.
Print Output:
Prints [20, 40]. STEP-BY-STEP EVALUATION:
Initial Tuple:
FINAL OUTPUT: tup = (1, 2, 3)
[20, 40] Concatenation:
tup += (4,)
KEY POINTS TO REMEMBER: Equivalent to: tup = tup + (4,)
Indexing in Slicing: Slicing starts at the Combines (1, 2, 3) with (4,) to form
start index and proceeds to the stop (1, 2, 3, 4).
index (exclusive). Print Output:
Step Parameter: A step greater than 1 Prints (1, 2, 3, 4).
skips elements in the sequence.
Zero-Based Indexing: Lists in Python FINAL OUTPUT:
use zero-based indexing, where the first (1, 2, 3, 4)
element is at index 0.
KEY POINTS TO REMEMBER: Returns 0
Immutability of Tuples: Tuples Combine Results:
themselves cannot be modified, but
sum_up(3) = 3 + sum_up(2) =
operations like concatenation create
new tuples. 3 + (2 + sum_up(1)) =
Single-Element Tuples: Always include 3 + (2 + (1 + sum_up(0)))
a trailing comma for single-element 3+2+1+0=6
tuples.
Tuple Concatenation: Use the + FINAL OUTPUT:
operator to combine tuples into a new 6
one.
KEY POINTS TO REMEMBER:
QUESTION 62: Recursive Functions: Always include a
def sum_up(n): base case to prevent infinite recursion.
if n == 0:
return 0
return n + sum_up(n - 1) QUESTION 63:
print(sum_up(3)) try:
print(10 / 0)
except ZeroDivisionError:
Answer: (a) 6
print("Error occurred")
finally:
CONCEPT INVOLVED: print("Done")
Recursion:
A function that calls itself is called Answer: (a) Error occurred Done
recursive.
Recursive functions must have a CONCEPT INVOLVED:
base case to terminate recursion. try-except-finally Block:
Here, the base case is if n == 0: The try block is used to execute
return 0. code that may raise exceptions.
The except block handles specific
Summation Logic:
exceptions. In this case, it handles
The function calculates the sum of ZeroDivisionError.
integers from n down to 0 The finally block is always executed,
recursively. regardless of whether an exception
Each recursive call reduces n by 1 was raised or handled.
until it reaches 0. ZeroDivisionError:
Occurs when attempting to divide a
STEP-BY-STEP EVALUATION: number by zero, as in 10 / 0.
First Call: sum_up(3) Order of Execution:
The try block is executed first.
n=3
If an exception is raised, control
Returns 3 + sum_up(2)
moves to the corresponding except
Second Call: sum_up(2) block.
n=2 After handling the exception, the
Returns 2 + sum_up(1) finally block is executed.
Third Call: sum_up(1)
n=1 STEP-BY-STEP EVALUATION:
Returns 1 + sum_up(0) try Block:
Base Case: sum_up(0) print(10 / 0) raises a
n=0 ZeroDivisionError.
Update lst[1]:
except Block: lst[1] = lst[2] + lst[0]
The ZeroDivisionError is caught by lst[2] = 3 (element at index 2)
the except ZeroDivisionError block. lst[0] = 1 (element at index 0)
print("Error occurred") outputs: lst[1] = 3 + 1 = 4
Error occurred. Final List:
finally Block: After the update, lst = [1, 4, 3].
Executes after the except block. Print Output:
print("Done") outputs: Done. Prints [1, 4, 3].
FINAL OUTPUT: FINAL OUTPUT:
Error occurred [1, 4, 3]
Done
KEY POINTS TO REMEMBER:
KEY POINTS TO REMEMBER: List Mutability: Lists can be modified
finally Block: Always executes, even if directly using indexing.
an exception is raised or handled. Indexing in Lists: Indexing allows access
Exception Handling: Ensure that the to and modification of individual
specific exception type is handled in elements in a list.
the except block. Expression Evaluation: Ensure that
Execution Flow: operations like lst[2] + lst[0] are
If no exception occurs, the finally evaluated correctly before assignment.
block executes after the try block.
If an exception occurs and is
handled, the finally block executes QUESTION 65:
after the except block. s1, s2 = "Good", "Morning"
print(s1 + " " + s2)
QUESTION 64: Answer: (b) Good Morning
lst = [1, 2, 3]
lst[1] = lst[2] + lst[0] CONCEPT INVOLVED:
print(lst) String Concatenation:
The + operator can be used to
Answer: (a) [1, 4, 3] concatenate (combine) strings.
In the expression s1 + " " + s2, it
CONCEPT INVOLVED: concatenates s1, a space " ", and s2.
List Indexing and Assignment: Spaces in Strings:
Lists in Python are mutable, so The space " " between s1 and s2
elements can be updated by ensures that there is a space
assigning new values to specific between the two words when
indices. printed.
The expression lst[1] = lst[2] + lst[0]
updates the element at index 1 with STEP-BY-STEP EVALUATION:
the sum of the elements at index 2 Assigning Values to s1 and s2:
and index 0. s1 = "Good"
s2 = "Morning"
STEP-BY-STEP EVALUATION: Concatenation and Print:
Initial List: s1 + " " + s2 results in the string
lst = [1, 2, 3] "Good Morning".
print(s1 + " " + s2) outputs: Good
Morning.
FINAL OUTPUT:
Good Morning FINAL OUTPUT:
Inner
KEY POINTS TO REMEMBER:
String Concatenation: Use the + KEY POINTS TO REMEMBER:
operator to join strings together. Nested Functions: Functions can be
Spaces in Strings: Explicitly add spaces defined inside other functions, and the
between words when needed by inner function is executed within the
including " " in the concatenation. outer function.
No Errors: This operation is valid in Returning Values: A function can return
Python as string concatenation the result of another function's call.
supports combining multiple string Scope of Inner Function: The inner
elements. function can only be used within the
outer function unless explicitly
returned or passed outside.
QUESTION 66:
def outer():
def inner(): QUESTION 67:
return "Inner"
a, b = True, False
return inner()
print(a and b, a or b, not a)
print(outer())
Answer: (a) Inner Answer: (d) False True False
CONCEPT INVOLVED: CONCEPT INVOLVED:
Nested Functions: Logical Operators:
In Python, functions can be defined and: Returns True if both operands
inside other functions. These are are True; otherwise, returns False.
called nested functions. or: Returns True if at least one
The inner function is accessible operand is True; otherwise, returns
only within the outer function. False.
Function Calls: not: Returns the opposite of the
The outer function returns the operand's truth value.
result of calling the inner function.
The inner function returns the STEP-BY-STEP EVALUATION:
string "Inner". a and b:
a = True, b = False
STEP-BY-STEP EVALUATION: a and b is True and False, which
outer() Function:
evaluates to False because both
The outer function defines an inner
operands need to be True for and to
function.
return True.
The inner() function returns the
string "Inner". a or b:
Return from outer(): a = True, b = False
The outer() function calls inner() a or b is True or False, which
and returns its result ("Inner"). evaluates to True because at least
return inner() within outer() causes one operand is True.
the string "Inner" to be returned. not a:
Print Output: a = True
print(outer()) prints the value not a is not True, which evaluates to
returned by outer(), which is False because not negates the truth
"Inner". value of a.
Final Output:
Read from the File:
print(a and b, a or b, not a) prints:
f = open("data.txt", "r"): Opens the
False True False.
file "data.txt" in read mode.
f.readlines(): Reads the lines from
FINAL OUTPUT:
the file and returns them as a list.
FALSE TRUE FALSE
The \n characters remain, so the
result is ['Line1\n', 'Line2'].
KEY POINTS TO REMEMBER:
f.close(): Closes the file after
and Operator: Returns True only if both
reading.
operands are True.
Print Output:
or Operator: Returns True if at least
The print(f.readlines()) statement
one operand is True.
prints the list of lines read from the
not Operator: Negates the truth value
file: ['Line1\n', 'Line2'].
of the operand.
FINAL OUTPUT:
['Line1\n', 'Line2']
QUESTION 68:
f = open("data.txt", "w") KEY POINTS TO REMEMBER:
f.write("Line1\nLine2") File Modes: "w" for writing, "r" for
f.close() reading.
f = open("data.txt", "r") Newline Character: The \n is preserved
print(f.readlines()) when writing and reading from files.
f.close() readlines() Method: Returns a list where
each element is a line from the file,
Answer: (a) ['Line1\n', 'Line2'] including the newline character (\n).
CONCEPT INVOLVED:
File Handling: QUESTION 69:
Write Mode ("w"): Opens the file for s = "Python"
writing, creating the file if it doesn't print(s.center(10, '-'))
exist and truncating it if it does.
Read Mode ("r"): Opens the file for Answer: (a) --Python--
reading. Concept Involved:
write(): Writes data to the file. str.center(width, fillchar):
readlines(): Reads all lines from the Centers the string within a specified
file and returns them as a list, with width.
each line as a separate string. Pads the string with the specified
fillchar (default is a space).
STEP-BY-STEP EVALUATION: The total width of the returned
Write to the File: string is specified by width.
f = open("data.txt", "w"): Opens the
file "data.txt" in write mode. STEP-BY-STEP EVALUATION:
f.write("Line1\nLine2"): Writes the Input String:
string "Line1\nLine2" to the file. The s = "Python": The string "Python"
\n creates a new line between has a length of 6.
"Line1" and "Line2". Specified Width:
f.close(): Closes the file after s.center(10, '-'): The total width is
writing. 10. Since "Python" is 6 characters
long, 4 additional characters (10 - 6
= 4) are needed for padding.
Padding Calculation: STEP-BY-STEP EVALUATION:
Padding is added equally on both len(lst):
sides. If the padding is not evenly Evaluates to 3 because the list has
divisible, extra padding is added to three elements.
the right. max(lst):
Here, 4 characters of padding are Evaluates to 3 because 3 is the
divided into 2 on the left and 2 on largest element in the list.
the right. min(lst):
Fill Character: Evaluates to 1 because 1 is the
The padding uses '-' as the fill smallest element in the list.
character. Print Output:
Result: --Python--. print(len(lst), max(lst), min(lst))
Print Output: prints: 3 3 1.
print(s.center(10, '-')) outputs: --
Python--. FINAL OUTPUT:
331
FINAL OUTPUT:
--Python-- KEY POINTS TO REMEMBER:
len() Function: Returns the count of
KEY POINTS TO REMEMBER: elements in the list.
center(width, fillchar) Method: Centers max() Function: Returns the largest
the string with padding on both sides. element in the list.
Default Padding Character: Space (' '), min() Function: Returns the smallest
unless a specific fillchar is provided. element in the list.
Uneven Padding: Extra padding is These functions work with any iterable
added to the right side if required. containing comparable elements.
QUESTION 70: QUESTION 71:
lst = [1, 2, 3] def factorial(n):
print(len(lst), max(lst), min(lst)) if n == 1:
return 1
Answer: (a) 3 3 1 else:
return n * factorial(n - 1)
CONCEPT INVOLVED: print(factorial(5))
len():
Returns the number of elements in Answer: (a) 120
a list.
In this case, lst = [1, 2, 3] contains 3 CONCEPT INVOLVED:
elements, so len(lst) evaluates to 3. Recursion:
max(): A function that calls itself to solve a
Returns the largest element in the smaller instance of the problem.
list. In this case, factorial() computes
Here, the largest element in [1, 2, 3] the factorial of a number using
is 3. recursion.
min(): Factorial:
Returns the smallest element in the The factorial of a number nnn is the
list. product of all positive integers less
Here, the smallest element in [1, 2, than or equal to nnn.
3] is 1. Formula: n!=n×(n−1)×⋯×1
STEP-BY-STEP EVALUATION: STEP-BY-STEP EVALUATION:
Function Call: Input Matrix:
factorial(5) initiates the recursion. matrix = [[1, 2], [3, 4]] represents:
Recursive Calls: [
factorial(5) returns 5×factorial(4) [1, 2],
factorial(4) returns 4×factorial(3) [3, 4]
factorial(3) returns 3×factorial(2) ]
factorial(2) returns 2×factorial(1) Accessing matrix[0][1]:
Base Case: matrix[0] selects the first sub-list:
factorial(1) returns 1 because n==1. [1, 2].
Return Values: matrix[0][1] selects the second
Substituting back: element in [1, 2]: 2.
factorial(2) returns 2×1=2 Accessing matrix[1][0]:
factorial(3) returns 3×2=6 matrix[1] selects the second sub-
factorial(4) returns 4×6= list: [3, 4].
factorial(5) returns 5×24=120 matrix[1][0] selects the first
Print Output: element in [3, 4]: 3.
print(factorial(5)) outputs 120. Print Output:
print(matrix[0][1], matrix[1][0])
FINAL OUTPUT: outputs: 2 3.
120
FINAL OUTPUT:
KEY POINTS TO REMEMBER: 23
Base Case in Recursion: Prevents
infinite recursion by stopping when a KEY POINTS TO REMEMBER:
specific condition is met. Nested List Indexing: Use two indices to
Recursive Case: Breaks the problem access elements: list[row][column].
into smaller subproblems. Zero-Based Indexing: Python lists use
Factorial: Defined as n!=n×(n−1)! with zero-based indexing.
1!=1. Syntax Errors: Ensure indices are
correctly used to avoid "IndexError."
QUESTION 72: QUESTION 73:
matrix = [[1, 2], [3, 4]] import math
print(matrix[0][1], matrix[1][0]) print(math.sqrt(16), math.ceil(4.2))
Answer: (a) 2 3 Answer: (b) 4.0 5
CONCEPT INVOLVED: CONCEPT INVOLVED:
Nested Lists: math.sqrt(x):
A nested list is a list of lists in Returns the square root of x.
Python. For math.sqrt(16), the result is
Elements are accessed using a pair 16=4.0\sqrt{16} = 4.016=4.0.
of indices: the first index selects the math.ceil(x):
sub-list, and the second index Returns the smallest integer greater
selects the element within that sub- than or equal to x.
list. For math.ceil(4.2), the result is 5
because 5 is the next integer after
4.2.
Importing the math Module: Conversion:
The math module provides int(y) converts the string "20" to the
mathematical functions, including integer 20.
sqrt and ceil. Addition:
x + int(y) becomes 10 + 20, which
STEP-BY-STEP EVALUATION: evaluates to 30.
Square Root Calculation: Print Output:
math.sqrt(16) evaluates to 4.0. print(x + int(y)) outputs: 30.
Ceiling Calculation:
math.ceil(4.2) evaluates to 5. FINAL OUTPUT:
Print Output: 30
print(math.sqrt(16), math.ceil(4.2))
outputs: 4.0 5. KEY POINTS TO REMEMBER:
Type Conversion with int(): Converts
FINAL OUTPUT: strings containing valid integers to
4.0 5 integers.
Strings Must Be Valid Integers: If y
KEY POINTS TO REMEMBER: contains non-numeric characters (e.g.,
math.sqrt(x) always returns a float even "20a"), int(y) raises a ValueError.
if the result is an integer. Arithmetic Operations Are Type-
math.ceil(x) rounds up to the nearest Specific: Adding an integer and a string
integer, regardless of the decimal part. without conversion will raise a
import math is required to use these TypeError.
functions, or it will raise a NameError.
QUESTION 75:
QUESTION 74:
f = open("file.txt", "w")
x = 10
f.write("Hello\nWorld")
y = "20"
f.close()
print(x + int(y))
f = open("file.txt", "r")
for line in f:
Answer: (b) 30
print(line.strip())
f.close()
CONCEPT INVOLVED:
Type Conversion with int():
Answer: (b) Hello followed by World on
The int() function converts a string
separate lines
containing a valid integer (e.g., "20")
into an integer.
CONCEPT INVOLVED:
Here, int("20") evaluates to 20.
File Handling in Python:
Addition of Integers:
open("file.txt", "w"): Opens the file
Once y is converted to an integer,
in write mode. If the file doesn't
the addition operation is performed
exist, it is created.
between x (10) and the integer
write("Hello\nWorld"): Writes
value of y (20).
"Hello" and "World" to the file,
separated by a newline character
STEP-BY-STEP EVALUATION:
\n.
Initial Variables:
open("file.txt", "r"): Opens the file in
x = 10 (integer).
read mode.
y = "20" (string).
QUESTION 76:
S = "Learning"
Looping Through File Lines:
print(S[-5:])
for line in f: Iterates over each line
in the file.
Answer: (a) rning
line.strip(): Removes leading and
trailing whitespace, including the
CONCEPT INVOLVED:
newline character. String Slicing:
print Statement: S[start:end] extracts a substring
Prints each line from the file after from the string S starting at index
stripping whitespace. start (inclusive) and ending at index
end (exclusive).
STEP-BY-STEP EVALUATION: Negative indices in slicing count
Write Operation: from the end of the string.
"Hello\nWorld" is written to file.txt. For example, S[-5:] means "start
The file now contains: from the 5th character from the
Hello end and go to the end of the
World string."
Read Operation: Indexing of String S = "Learning":
File is reopened in read mode. S = "Learning"
Loop iterates over each line in the Indices:
file: L e a r n i n g
Line 1: "Hello\n" → strip() → 0 1 2 3 4 5 6 7
-8 -7 -6 -5 -4 -3 -2 -1
"Hello".
Line 2: "World" → strip() →
STEP-BY-STEP EVALUATION:
"World".
Slicing:
Print Statements:
S[-5:]: Start from index -5 ('r') and
Line 1: "Hello" is printed.
continue to the end of the string.
Line 2: "World" is printed. Substring: 'rning'.
Print Output:
FINAL OUTPUT: print(S[-5:]) outputs: rning.
Hello followed by World on
separate lines. FINAL OUTPUT:
rning
KEY POINTS TO REMEMBER:
File Modes: KEY POINTS TO REMEMBER:
"w": Write mode (overwrites existing Negative Indices:
content). Negative indices start from the end
"r": Read mode. of the string (-1 for the last
strip() Removes Whitespace: character).
Useful for cleaning file content Slicing Mechanics:
when reading line by line. Omitting the end index (S[-5:])
Newline Behavior in Files: includes all characters from the
\n creates new lines in the file start index to the end of the string.
Inclusive and Exclusive Nature:
content.
Start index is inclusive, and the end
index (if specified) is exclusive.
QUESTION 77: QUESTION 78:
words = ["I", "love", "Python"] D = {"A": {"B": 5}, "C": 10}
print(" ".join(words)) print(D["A"]["B"])
Answer: (a) I love Python Answer: (a) 5
CONCEPT INVOLVED: CONCEPT INVOLVED:
join() Method: Nested Dictionaries:
Used to concatenate elements of an A dictionary can contain another
iterable (like a list) into a single dictionary as its value.
string, with a specified separator. Example:
Syntax: "separator".join(iterable) D = {"A": {"B": 5}, "C": 10}
" ".join(words) joins the elements of The key "A" maps to another
the list words with a single space (" dictionary {"B": 5}.
") as the separator. The key "C" maps to the integer
Behavior of join() with Strings: 10.
join() concatenates all elements of Accessing Nested Elements:
the list in order, inserting the Access outer dictionary elements
separator between them. using D[key].
Access elements of the inner
STEP-BY-STEP EVALUATION: dictionary using D[outer_key]
List words: [inner_key].
Contains ["I", "love", "Python"].
" ".join(words): STEP-BY-STEP EVALUATION:
Concatenates elements with a Dictionary D:
space: D = {"A": {"B": 5}, "C": 10}:
"I" + " " + "love" + " " + "Python" = "A" maps to {"B": 5}.
"I love Python" "C" maps to 10.
Print Statement: Accessing Inner Value:
print("I love Python") outputs: I love D["A"] retrieves the inner
Python. dictionary: {"B": 5}.
D["A"]["B"] retrieves the value of
FINAL OUTPUT: the key "B" in the inner dictionary:
I love Python 5.
Print Statement:
KEY POINTS TO REMEMBER: print(D["A"]["B"]) outputs: 5.
join() Combines Elements:
Works only with iterables containing FINAL OUTPUT:
strings. 5
Raises an error if any element is not
a string. KEY POINTS TO REMEMBER:
Separator Flexibility: Nested Dictionaries:
You can use any string as a Useful for representing hierarchical
separator (e.g., "".join(words) would data structures.
produce "IlovePython"). Key Lookup:
Immutable Strings: Ensure all keys exist to avoid
join() creates a new string without KeyError.
modifying the original list. Syntax:
Use square brackets to access both
outer and inner dictionary keys.
QUESTION 79:
Multiplication and Printing:
S = "DataScience"
In each iteration, i * j is computed
print(S[::-2])
and printed with a trailing comma.
Answer: (b) eniStD
STEP-BY-STEP EVALUATION:
Outer Loop (i):
CONCEPT INVOLVED:
Iterates i = 1, 2, 3.
String Slicing ([::-2]):
Inner Loop (j):
[::-2] reverses the string (S[::-1]) and
For each value of i, j iterates 2, 4.
then skips every second character
Combined Iterations:
starting from the last.
When i = 1: 1 * 2 = 2, 1 * 4 = 4.
Reversed String:
When i = 2: 2 * 2 = 4, 2 * 4 = 8.
"DataScience"[::-1] gives
When i = 3: 3 * 2 = 6, 3 * 4 = 12.
"ecneicSataD".
Print Statement:
Skipping Characters:
Outputs all results separated by
From "ecneicSataD", every second
commas: 2, 4, 4, 8, 6, 12,.
character is taken: "eniStD".
FINAL OUTPUT:
STEP-BY-STEP EVALUATION:
2, 4, 4, 8, 6, 12,
Original String: "DataScience".
Reverse the string: "ecneicSataD".
KEY POINTS TO REMEMBER:
Skip every second character: "eniStD".
range(start, stop, step):
Generates numbers from start
FINAL OUTPUT:
(inclusive) to stop (exclusive) with a
eniStD
step.
Nested Loops:
KEY POINTS TO REMEMBER:
Inner loop executes completely for
Negative Step in Slicing ([::-1]):
every iteration of the outer loop.
Reverses the order of elements in
Output Formatting:
the string.
print(..., end=", ") ensures outputs
Combination of Reversal and Skipping:
are printed on the same line with
[::-2] combines reversal and
commas.
skipping of characters.
Indexes Work Backward:
QUESTION 81:
In negative slicing, indices count
double = lambda x: x * 2
backward from -1.
print(double(7))
QUESTION 80: Answer: (a) 14
for i in range(1, 4):
for j in range(2, 5, 2): CONCEPT INVOLVED:
print(i * j, end=", ") Lambda Function:
lambda x: x * 2 defines an
CONCEPT INVOLVED: anonymous function that takes one
Nested Loops: argument x and returns x multiplied
The outer loop iterates over i from 1 by 2.
to 3 (inclusive). Calling the Lambda Function:
The inner loop iterates over j from 2 double(7) calls the lambda function
to 4 with a step of 2, i.e., j takes with 7 as the argument, and the
values 2 and 4. result is 7 * 2 = 14.
STEP-BY-STEP EVALUATION: Infinite Recursion:
Define the Lambda Function: The function does not handle
double = lambda x: x * 2 defines a negative odd numbers properly,
function double(x) that multiplies leading to infinite recursion, as it
its argument x by 2. continuously subtracts 2 without
Call the Lambda Function:
reaching an even number.
double(7) calls the function with 7,
and the result is 14.
Print the Result: STEP-BY-STEP EVALUATION:
The function returns 14, which is First Call (n = 5):
printed. 5 is odd, so the function calls
custom_sum(3).
FINAL OUTPUT: Second Call (n = 3):
14 3 is odd, so the function calls
custom_sum(1).
KEY POINTS TO REMEMBER: Third Call (n = 1):
Lambda Functions:
1 is odd, so the function calls
Useful for creating small,
custom_sum(-1).
anonymous functions that are not
bound to a name. Fourth Call (n = -1):
Syntax: lambda argument(s): -1 is odd, so the function calls
expression. custom_sum(-3).
No Type Conversion: This process continues indefinitely for
The result is an integer 14 as x * 2 all odd numbers, causing a
does not cause any type conversion RecursionError once the maximum
in this case. recursion depth is exceeded.
FINAL OUTPUT:
QUESTION 82: The code results in a RecursionError
def custom_sum(n):
because the recursion never reaches
if n % 2 == 0:
the base case (an even number) and
return n
return n + custom_sum(n - 2) runs infinitely for odd numbers.
print(custom_sum(5))
KEY POINTS TO REMEMBER:
Answer: (d) Error Recursion Depth Limitation:
Python has a limit on how deep
CONCEPT INVOLVED: recursive calls can go (usually
Recursion: 1000). This code results in infinite
A function calling itself with recursion for odd numbers and will
modified arguments. It continues to
eventually cause a RecursionError.
call itself until a base case is met.
Proper Base Case Handling:
Base Case:
The base case for recursion here Ensure that the recursion has a
checks if the number n is even (n % proper base case for all possible
2 == 0). If true, the function returns inputs, including negative or odd
n. numbers, to prevent infinite
recursion.
QUESTION 83: QUESTION 84:
name = "CBSE Computer Science" s = "Hello"
print(name.count('e')) print(s * 2)
Answer: (a) 3
Answer: (a) HelloHello
CONCEPT INVOLVED:
CONCEPT INVOLVED:
count() method:
The count() method in Python returns String Multiplication:
the number of occurrences of a In Python, the multiplication operator *
substring in the string. It takes the can be used to repeat a string multiple
substring as an argument and counts times. If s is a string and n is an integer,
how many times it appears in the string. s * n will repeat the string s n times.
STEP-BY-STEP EVALUATION: STEP-BY-STEP EVALUATION:
Input String: Input String:
The input string is "CBSE Computer
The input string is "Hello".
Science".
Multiplication Operation:
Method Call:
The expression s * 2 repeats the string s
name.count('e') counts the occurrences
of the letter 'e' in the string. two times.
Occurrences of 'e': Result:
In the word "CBSE", there is 1 'e'. "Hello" * 2 results in the string
In the word "Computer", there is 1 "HelloHello", which is the string s
'e'. repeated twice.
In the word "Science", there is 1 'e'.
Total Occurrences of 'e': FINAL OUTPUT:
The letter 'e' appears 3 times in the The output of the code is HelloHello
string.
because the string "Hello" is repeated 2
times.
FINAL OUTPUT:
The output of the code is 3 since there
are 3 occurrences of the letter 'e' in the KEY POINTS TO REMEMBER:
string "CBSE Computer Science". String multiplication (*) repeats the
string as many times as specified by the
KEY POINTS TO REMEMBER: integer.
The count() method counts non- It does not add a space or separator
overlapping occurrences of the between the repeated strings unless
specified substring. explicitly defined.
It is case-sensitive, meaning 'e' is
different from 'E'.
name.count('e') counts only the
lowercase 'e' characters in the string.
QUESTION 85: QUESTION 86:
lst = [5, 10, 15] f = open("example.txt", "w")
lst.reverse() f.write("Python\nProgramming")
print(lst) f.close()
f = open("example.txt", "r")
print(f.readline().strip())
Answer: (a) [15, 10, 5]
f.close()
CONCEPT INVOLVED: Answer: (a) Python
reverse() Method:
Reverses the elements of a list in CONCEPT INVOLVED:
place, modifying the original list. File Handling:
Syntax: write():
list.reverse() Writes the given string to the
This method does not return a new file.
list; it modifies the original list and In this case,
"Python\nProgramming" writes
returns None.
two lines: "Python" on the first
line and "Programming" on the
STEP-BY-STEP EVALUATION:
second line.
Original List: readline():
lst = [5, 10, 15] Reads only the first line of the
Apply reverse(): file.
lst.reverse() reverses the order of strip():
elements: Removes leading and trailing
lst = [15, 10, 5] whitespaces, including newline
Print Statement: characters (\n).
print(lst) outputs the modified list:
STEP-BY-STEP EVALUATION:
[15, 10, 5]
File Writing:
The file example.txt is opened in
FINAL OUTPUT:
write mode ("w") and
[15, 10, 5] "Python\nProgramming" is written
to the file.
KEY POINTS TO REMEMBER: After this step, the file content is:
reverse(): Python
Directly modifies the original list in Programming
place. File Reading:
Returns None (does not create a The file example.txt is reopened in
new list). read mode ("r").
f.readline() reads the first line:
To create a reversed copy without
"Python\n"
modifying the original list, use slicing:
reversed_lst = lst[::-1]
Apply strip(): STEP-BY-STEP EVALUATION:
strip() removes the trailing newline Original String:
character (\n): text = "Programming is fun"
"Python" Apply replace():
Print Statement: text.replace("fun", "amazing")
print(f.readline().strip()) outputs: searches for the substring "fun" in
Python text and replaces it with "amazing".
The resulting string is:
FINAL OUTPUT: "Programming is amazing"
Python Print Statement:
print(text.replace("fun", "amazing"))
KEY POINTS TO REMEMBER: outputs:
write(): Programming is amazing
Adds text to the file exactly as
provided. Use \n to add new lines. FINAL OUTPUT:
readline(): Programming is amazing
Reads only the first line of the file,
including the newline character (\n). KEY POINTS TO REMEMBER:
strip(): Strings in Python are immutable:
Removes leading and trailing Methods like replace() return a new
spaces, tabs, and newline string instead of modifying the
characters. original.
replace():
Replaces all occurrences of the old
QUESTION 87:
substring with the new substring.
text = "Programming is fun"
If the old substring does not exist,
print(text.replace("fun", "amazing"))
the original string is returned
unchanged.
Answer: (a) Programming is amazing
CONCEPT INVOLVED: QUESTION 88:
replace() Method: t = (10, 20, 30, 40)
Replaces all occurrences of a print(t[1:3])
specified substring with another
substring. Answer: (a) (20, 30)
Syntax:
string.replace(old, new) CONCEPT INVOLVED:
This method does not modify the Tuple Slicing:
original string but returns a new Similar to lists, tuples support
string with the replacements. slicing using the syntax:
tuple[start:end]
This creates a new tuple containing QUESTION 89:
elements from the start index def greet(name="Guest"):
(inclusive) up to the end index return f"Hello, {name}!"
(exclusive). print(greet("Alice"))
print(greet())
STEP-BY-STEP EVALUATION:
Tuple Definition: Answer: (a) Hello, Alice! followed by
t = (10, 20, 30, 40) is a tuple with Hello, Guest!
four elements.
Slice the Tuple: CONCEPT INVOLVED:
t[1:3] extracts elements starting at Default Arguments:
index 1 up to (but not including) A function can have default values
index 3: for parameters.
Index 1 → 20 If an argument is not provided when
Index 2 → 30 the function is called, the default
Resulting Tuple: value is used.
The sliced tuple is: F-Strings:
(20, 30) Allows embedding expressions
Print Statement: directly into string literals using {}.
print(t[1:3]) outputs:
(20, 30) STEP-BY-STEP EVALUATION:
Function Definition:
FINAL OUTPUT: greet(name="Guest") defines a
(20, 30) function with a default parameter
name="Guest".
KEY POINTS TO REMEMBER: If no argument is passed for name,
Tuples Support Slicing: it defaults to "Guest".
The slicing syntax works the same First Function Call:
as for lists, but the result is always a greet("Alice"):
tuple (not a list). The parameter name is explicitly
Slicing Behavior: set to "Alice".
The start index is inclusive, and the Returns:
end index is exclusive. "Hello, Alice!"
Negative indices can also be used print() outputs:
for slicing. Hello, Alice!
Second Function Call:
greet():
No argument is provided, so the
default value of name is "Guest".
Returns: Apply sort():
"Hello, Guest!" numbers.sort() arranges the elements in
print() outputs: ascending order:
Hello, Guest! [5, 10, 15]
Print Statement:
FINAL OUTPUT: print(numbers) outputs the sorted list:
Hello, Alice! [5, 10, 15]
Hello, Guest!
FINAL OUTPUT:
KEY POINTS TO REMEMBER: [5, 10, 15]
Default Parameters:
Default values are used when no KEY POINTS TO REMEMBER:
argument is provided for a sort():
parameter. Directly modifies the original list to
Explicitly provided arguments arrange the elements in ascending
override the default values. order.
F-Strings: Returns None.
Simplify string formatting by Default Behavior:
embedding expressions directly For numeric lists, sorting is performed
into the string. in ascending order.
QUESTION 90: QUESTION 91:
numbers = [10, 5, 15] print(5 > 3 and 3 < 2 or 10 == 10)
numbers.sort()
print(numbers) Answer: (a) True
Answer: (a) [5, 10, 15] CONCEPT INVOLVED:
Logical Operators and Precedence:
CONCEPT INVOLVED: Order of Evaluation:
sort() Method: and is evaluated before or.
Sorts the elements of a list in Logical expressions follow short-circuit
ascending order by default. evaluation:
Modifies the original list in place For and, if the first condition is False,
(does not return a new list). the rest is not evaluated.
For numbers, sorting is done based For or, if the first condition is True, the
on numeric values. rest is not evaluated.
STEP-BY-STEP EVALUATION: STEP-BY-STEP EVALUATION:
Original List: Expression:
numbers = [10, 5, 15] 5 > 3 and 3 < 2 or 10 == 10
Step 1 - Evaluate 5 > 3: readlines():
5 > 3 = True Reads all lines from the file and
Step 2 - Evaluate 3 < 2: returns a list where each
3 < 2 = False element is a string representing
Step 3 - Combine with and: a line, including the newline
True and False = False characters (\n).
Step 4 - Evaluate 10 == 10:
10 == 10 = True STEP-BY-STEP EVALUATION:
Step 5 - Combine with or: File Writing:
False or True = True The file data.txt is opened in write
mode ("w").
FINAL OUTPUT: writelines(["Hello\n", "World\n",
True "Python\n"]) writes:
Hello
KEY POINTS TO REMEMBER: World
Logical Operator Precedence: Python
and is evaluated before or. File Reading:
Short-Circuit Evaluation: The file data.txt is reopened in
For or, evaluation stops as soon as read mode ("r").
a True value is encountered. f.readlines() reads all lines and
For and, evaluation stops as soon stores them in a list:
as a False value is encountered. ['Hello\n', 'World\n', 'Python\n']
Print Statement:
print(f.readlines()) outputs the list:
QUESTION 92:
['Hello\n', 'World\n', 'Python\n']
with open("data.txt", "w") as f:
f.writelines(["Hello\n", "World\n",
FINAL OUTPUT:
"Python\n"])
['Hello\n', 'World\n', 'Python\n']
with open("data.txt", "r") as f:
KEY POINTS TO REMEMBER:
print(f.readlines())
writelines():
Writes each string in the list to the
Answer: (a) ['Hello\n', 'World\n',
file. Explicitly include \n for new
'Python\n']
lines.
readlines():
Concept Involved:
Returns a list of strings, each
File Handling:
representing a line in the file,
writelines():
including \n.
Writes a list of strings to a file
without automatically adding
newline characters. Newlines
must be explicitly included (\n).
KEY POINTS TO REMEMBER:
QUESTION 93: Slicing Behavior:
lst = [10, 20, 30, 40, 50] A positive step skips elements in
print(lst[::3])
the forward direction.
Default start is the first element
Answer: (a) [10, 40]
(index 0).
Default end is the last element of
CONCEPT INVOLVED:
the list.
List Slicing:
Step Size:
Syntax: lst[start:end:step]
A step value of 3 means every third
start: The index where slicing
begins (default is 0). element is included in the resulting
end: The index where slicing list.
ends (default is the end of the
list).
step: The interval between QUESTION 94:
elements to include in the A = {1, 2, 3}
result. B = {3, 4, 5}
print(A | B, A & B)
STEP-BY-STEP EVALUATION:
Expression: Answer: (a) {1, 2, 3, 4, 5} {3}
lst[::3] means:
start: Default (0), so slicing CONCEPT INVOLVED:
begins at the first element. Set Operations:
end: Default (end of the list), so Union (|):
slicing goes to the last element. Combines all unique elements
step: 3, so every third element from both sets.
is selected. Syntax: A | B or A.union(B).
List Elements: Intersection (&):
Original list: [10, 20, 30, 40, 50] Retrieves only the common
Start at index 0 (10) and pick every elements from both sets.
3rd element:
Syntax: A & B or
Index 0 → 10
A.intersection(B).
Index 3 → 40
Resulting List:
STEP-BY-STEP EVALUATION:
[10, 40]
Sets Definition:
Print Statement:
A = {1, 2, 3}
print(lst[::3]) outputs:
B = {3, 4, 5}
[10, 40]
Union (A | B):
FINAL OUTPUT: Combines all unique elements
[10, 40] from A and B:
{1, 2, 3} ∪ {3, 4, 5} = {1, 2, 3, 4, 5}
Intersection (A & B): split():
Retrieves the common elements Splits the string into a list of
from A and B: words using whitespace
{1, 2, 3} ∩ {3, 4, 5} = {3} (spaces, newlines, tabs) as the
delimiter.
Print Statement:
print(A | B, A & B) outputs:
STEP-BY-STEP EVALUATION:
{1, 2, 3, 4, 5} {3}
File Writing:
The file data.txt is opened in write
FINAL OUTPUT: mode ("w") and the string
{1, 2, 3, 4, 5} {3} "Python\nProgramming" is written.
The content of the file becomes:
KEY POINTS TO REMEMBER: Python
Union (|): Programming
Includes all unique elements from File Reading:
both sets. The file is reopened in read mode
("r").
Intersection (&):
f.read() reads the entire content of
Includes only elements present in
the file as a single string:
both sets.
"Python\nProgramming"
Order of operations in the print Apply split():
statement does not affect the results. f.read().split() splits the string into
words based on whitespace
(including newlines).
QUESTION 95: The resulting list is:
f = open("data.txt", "w") ['Python', 'Programming']
f.write("Python\nProgramming") Print Statement:
f.close() print(f.read().split()) outputs:
f = open("data.txt", "r") ['Python', 'Programming']
print(f.read().split())
FINAL OUTPUT:
['Python', 'Programming']
Answer: (a) ['Python', 'Programming']
KEY POINTS TO REMEMBER:
CONCEPT INVOLVED: write():
File Handling: Writes the string as-is, including
write(): newline characters.
Writes a string to a file. Newline read():
characters (\n) are treated as Reads the entire content of the file
line breaks. into a single string.
read(): split():
Reads the entire content of the Splits the string into a list of words
using whitespace as the default
file as a single string.
delimiter.
QUESTION 96: KEY POINTS TO REMEMBER:
D = {"a": 10, "b": 20, "c": 30} Key Exists:
print(D.get("b", 0), D.get("d", 0)) If the key exists, get() returns its
associated value.
Answer: (a) 20 0 Key Does Not Exist:
If the key does not exist, the
CONCEPT INVOLVED: provided default_value is returned.
get() Method in Dictionaries: If no default_value is specified,
Syntax: dictionary.get(key, None is returned.
default_value)
QUESTION 97:
Retrieves the value associated
for i in range(4):
with the specified key.
if i == 2:
If the key exists, the corresponding
continue
value is returned. print(i, end=", ")
If the key does not exist, the
default_value is returned. If no Answer: (a) 0, 1, 3,
default_value is provided, None is
returned. CONCEPT INVOLVED:
for Loop:
STEP-BY-STEP EVALUATION: Iterates over a sequence or range of
Dictionary Definition: numbers.
D = {"a": 10, "b": 20, "c": 30} range(4) generates the sequence: 0,
defines a dictionary with three 1, 2, 3.
key-value pairs: continue Statement:
"a": 10, "b": 20, "c": 30 Skips the current iteration of the
First Call - D.get("b", 0): loop when the condition is met.
The key "b" exists in the dictionary The loop proceeds to the next
with a value of 20. iteration, bypassing the code below
Returns: 20. the continue statement for that
iteration.
Second Call - D.get("d", 0):
The key "d" does not exist in the
STEP-BY-STEP EVALUATION:
dictionary.
range(4):
The default_value (0) is returned.
Generates the numbers: 0, 1, 2, 3.
Print Statement:
Loop Iterations:
print(D.get("b", 0), D.get("d", 0))
Iteration 1 (i = 0):
outputs:
Condition i == 2 is False.
20 0 print(0, end=", ") → Output: 0, .
Iteration 2 (i = 1):
FINAL OUTPUT: Condition i == 2 is False.
20 0 print(1, end=", ") → Output: 0, 1, .
Iteration 3 (i = 2):
Only elements that satisfy the if
Condition i == 2 is True.
condition are included in the new
continue skips the print()
list.
statement for this iteration.
Iteration 4 (i = 3):
STEP-BY-STEP EVALUATION:
Condition i == 2 is False.
Original List:
print(3, end=", ") → Output: 0, 1,
numbers = [1, 2, 3, 4, 5]
3, .
List Comprehension:
[x**2 for x in numbers if x % 2 == 0]:
FINAL OUTPUT:
Iterates through each element x
0, 1, 3,
in numbers.
Checks if x % 2 == 0 (i.e., x is
KEY POINTS TO REMEMBER:
even).
continue:
If the condition is True,
Skips the remaining code in the
computes x**2 (the square of x)
current iteration and moves to the
and adds it to the result list.
next iteration.
Filter Even Numbers:
end Parameter in print():
x % 2 == 0 filters the even numbers:
end=", " ensures that all values are
2, 4.
printed on the same line, separated
Compute Squares:
by a comma and space.
For x = 2: 2**2 = 4.
For x = 4: 4**2 = 16.
QUESTION 98: Result:
numbers = [1, 2, 3, 4, 5] result = [4, 16]
result = [x**2 for x in numbers if x % 2 == Print Statement:
0] print(result) outputs:
print(result) [4, 16]
Answer: (a) [4, 16] FINAL OUTPUT:
[4, 16]
CONCEPT INVOLVED:
List Comprehension with Conditions: KEY POINTS TO REMEMBER:
A concise way to create a new list List Comprehension:
by applying an operation to each Combines filtering (if condition) and
element of an existing list with a transformation (x**2) in a single line.
condition. Filtering:
Syntax: Only even numbers (x % 2 == 0) are
[expression for item in iterable if included in the result.
condition]
QUESTION 99: QUESTION 100:
tuple1 = (1, 2, 3) s = "Mississippi"
tuple1[0] = 4 print(s.count("s"))
print(tuple1)
Answer: (a) 4
Answer: (c) Error
CONCEPT INVOLVED:
CONCEPT INVOLVED: String Methods in Python:
Tuples are Immutable: The count() method in Python
Tuples in Python are immutable, returns the number of occurrences
meaning their elements cannot be of a substring in the given string.
modified after creation.
STEP-BY-STEP EVALUATION:
STEP-BY-STEP EVALUATION: Expression:
Expression: s = "Mississippi"
tuple1 = (1, 2, 3) s.count("s")
tuple1[0] = 4 Step 1 - Initialize the string:
Step 1 - Creating the tuple: The string s is assigned the value
A tuple tuple1 is created with the "Mississippi".
elements (1, 2, 3). Step 2 - Use the count() method:
Step 2 - Attempt to modify the tuple: The method s.count("s") counts how
The code attempts to change the many times the substring "s"
first element of the tuple: tuple1[0] appears in the string "Mississippi".
= 4. Step 3 - Count occurrences of "s":
Step 3 - Error raised: In the string "Mississippi", the
Since tuples are immutable, character "s" appears 4 times.
attempting to change an element
results in a TypeError. FINAL OUTPUT:
The result of s.count("s") is 4.
FINAL OUTPUT:
An error will occur when trying to KEY POINTS TO REMEMBER:
assign a new value to an element in the The count() method counts all
tuple. occurrences of the specified substring
in the string.
KEY POINTS TO REMEMBER: It is case-sensitive, so "s" and "S" would
Tuples in Python are immutable, be counted separately.
meaning you cannot modify their
elements after creation.
Any attempt to modify a tuple will
result in a TypeError.
QUESTION 101:
def square(n):
return n * n
def double(n):
return n + n
print(square(double(3)))
Answer: (a) 36
CONCEPT INVOLVED:
Function Call and Return Values:
Functions return values that can be
used as arguments in other functions.
The output of one function can be
passed directly into another function.
STEP-BY-STEP EVALUATION:
Expression:
square(double(3))
Step 1 - Evaluate the inner function
double(3):
The function double(n) returns n +
n.
double(3) returns 3 + 3 = 6.
Step 2 - Pass the result to the outer
function square(6):
The function square(n) returns n * n.
square(6) returns 6 * 6 = 36.
FINAL OUTPUT:
The result of square(double(3)) is 36.
KEY POINTS TO REMEMBER:
Functions can be nested, where the
output of one function is passed as
input to another function.
The inner function (double(3)) is
evaluated first, and then its result is
passed to the outer function
(square(6)).