Python Programming —
Complete Answer Key
Part A: Theory Questions
1. Basic Datatypes in Python
Python has several built-in datatypes:
int – whole numbers, e.g. x = 10
float – decimal numbers, e.g. y = 3.14
complex – numbers with real and imaginary parts,
e.g. z = 2 + 3j
str – sequence of characters, e.g. name =
"Akshay"
bool – True or False
list – ordered, mutable collection, e.g. [1, 2, 3]
tuple – ordered, immutable collection, e.g. (1, 2,
3)
set – unordered collection of unique items, e.g.
{1, 2, 3}
dict – key-value pairs, e.g. {"a": 1, "b": 2}
NoneType – represents absence of value, None
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hi")) # <class 'str'>
print(type([1,2])) # <class 'list'>
2. Type Conversion (Implicit vs Explicit)
Type conversion means changing a value from one
datatype to another.
Implicit conversion: Python automatically
converts a smaller/compatible type to a larger
one, with no data loss, during operations.
a = 5 # int
b = 2.5 # float
c = a + b # Python auto-converts 'a' to
float
print(c, type(c)) # 7.5 <class 'float'>
Explicit conversion (type casting): The
programmer manually converts using functions
like int() , float() , str() .
x = "10"
y = int(x) + 5 # explicit conversion
of string to int
print(y) # 15
z = str(100) + " apples"
print(z) # "100 apples"
Implicit Explicit
Done automatically by Done manually by
Python programmer
Programmer must ensure
No data loss (usually)
validity
int + float → int(x) , float(x) ,
float str(x)
3. String Operations
s1 = "Hello"
s2 = "World"
# Slicing
print(s1[0:3]) # 'Hel'
print(s1[-3:]) # 'llo'
# Concatenation
print(s1 + " " + s2) # 'Hello World'
# Repetition
print(s1 * 3) # 'HelloHelloHello'
# Comparison
print(s1 == "Hello") # True
print(s1 < s2) # True (lexicographic
comparison, 'H' < 'W')
4. Mutability in Lists
Lists are mutable — their contents can be changed
after creation.
list1 = [1, 2, 3]
list2 = list1 # reference, NOT a
clone
[Link](4)
print(list1) # [1, 2, 3, 4] ->
original also changed!
# Creating a real clone
list3 = [Link]() # or list1[:], or
list(list1)
[Link](99)
print(list1) # [1, 2, 3, 4]
unaffected
print(list3) # [1, 2, 3, 4,
99]
list2 = list1 copies the reference (both point to
the same object), while .copy() , slicing [:] , or
list() creates an independent clone.
5. Exceptions and Exception Handling
An exception is an error that occurs during program
execution, disrupting normal flow (e.g., dividing by
zero, opening a missing file).
Python handles exceptions using try-except :
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input, enter a number!")
else:
print("Result:", result)
finally:
print("Execution complete.")
try : code that might raise an error
except : handles specific error types
else : runs if no exception occurred
finally : always runs (cleanup code)
6. Class, Object, Instance Variables
Class: A blueprint for creating objects, defining
attributes and methods.
Object: An instance of a class — an actual entity
created from the blueprint.
Instance variable: A variable that belongs to a
specific object (unique per object).
class Car:
def __init__(self, brand, color):
[Link] = brand # instance
variable
[Link] = color # instance
variable
car1 = Car("Toyota", "Red") # object
car2 = Car("Honda", "Blue") # object
print([Link], [Link]) # Toyota
Red
print([Link], [Link]) # Honda
Blue
7. Program, Debugging, and Error Types
A program is a set of instructions written in a
programming language that a computer executes to
perform a task.
a) Debugging: The process of finding and fixing
errors (bugs) in code.
b) Syntax Errors: Errors due to incorrect
grammar/rules of the language (e.g., missing
colon). Detected before execution.
if True
print("hi") # SyntaxError: missing
colon
c) Runtime Errors: Errors that occur while the
program is running (e.g., division by zero).
print(10/0) # ZeroDivisionError
d) Semantic Errors: Code runs without crashing
but produces wrong/unintended results (logic
errors).
def add(a, b):
return a - b # wrong operator, no
crash, but wrong result
e) Runtime Errors (repeated in question): same as
(c).
8. Step-by-step Expression Evaluation
a) 18 + (5 // 2) + 8 % 2
1. 5 // 2 = 2 (floor division)
2. 8 % 2 = 0 (modulus)
3. 18 + 2 + 0 = 20
Result = 20
b) (2**3)**2 + 3
1. 2**3 = 8
2. 8**2 = 64
3. 64 + 3 = 67
Result = 67
9. Decision-Making Statements
a) if–else
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
b) if–elif–else
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
10. break and continue
# break - exits the loop entirely
for i in range(1, 10):
if i == 5:
break
print(i) # prints 1 2 3 4
# continue - skips current iteration,
continues loop
for i in range(1, 6):
if i == 3:
continue
print(i) # prints 1 2 4 5
11. Lists
A list is an ordered, mutable collection that can hold
items of different datatypes.
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple',
'banana', 'cherry']
[Link]("mango")
print(fruits[1]) # banana
12. Tuples — Packing and Unpacking
A tuple is an ordered, immutable collection defined
with parentheses () .
# Packing - combining values into a tuple
person = ("Akshay", 25, "Engineer")
# Unpacking - extracting values into
variables
name, age, profession = person
print(name) # Akshay
print(age) # 25
print(profession) # Engineer
13. File Handling
File handling allows a program to create, read, write,
and manipulate files stored on disk.
# Opening and reading a file
file = open("[Link]", "r") # 'r' =
read mode
content = [Link]()
print(content)
[Link]()
# Better approach - using 'with' (auto-
closes file)
with open("[Link]", "r") as file:
for line in file:
print([Link]())
Common modes: "r" (read), "w" (write, overwrites),
"a" (append), "r+" (read/write).
Part B: Scenario-Based Questions
1. Arithmetic Expression & String
Concatenation Error
An arithmetic expression combines
numbers/variables with operators ( + , - , * , / ) to
compute a value.
print('Hello' + 100 + 'how are you')
This produces a TypeError : can only concatenate
str (not "int") to str .
Reason: The + operator between strings performs
concatenation, but Python does not automatically
convert int to str (no implicit conversion for this
case). You must explicitly convert: 'Hello' +
str(100) + 'how are you' .
2. Arithmetic Operations Menu & Senior Citizen
Check
# Program 1: Arithmetic operations
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number:
"))
print("1-Add 2-Subtract 3-Multiply 4-
Divide")
choice = int(input("Enter choice: "))
if choice == 1:
print("Result:", num1 + num2)
elif choice == 2:
print("Result:", num1 - num2)
elif choice == 3:
print("Result:", num1 * num2)
elif choice == 4:
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error: Division by zero")
else:
print("Invalid choice")
# Program 2: Senior citizen check
name = input("Enter name: ")
birth_year = int(input("Enter year of
birth: "))
current_year = 2026
age = current_year - birth_year
if age >= 60:
print(f"{name} is a senior citizen.")
else:
print(f"{name} is not a senior
citizen.")
3. Traffic Light Simulation
signal = input("Enter signal
(red/yellow/green): ").lower()
if signal == "red":
print("Stop")
elif signal == "yellow":
print("Get Ready")
elif signal == "green":
print("Go")
else:
print("Invalid signal")
4. Employee Tuple
employee = (101, "Ravi Kumar", "IT", 55000)
def display_employee(emp):
print("ID:", emp[0])
print("Name:", emp[1])
print("Department:", emp[2])
print("Salary:", emp[3])
def get_name_salary(emp):
return (emp[1], emp[3])
display_employee(employee)
name_salary = get_name_salary(employee)
print("Name & Salary:", name_salary)
5. Read Text File — Lines, Words, Characters
try:
with open("[Link]", "r") as file:
content = [Link]()
lines = [Link]()
words = [Link]()
print("Number of lines:",
len(lines))
print("Number of words:",
len(words))
print("Number of characters:",
len(content))
except FileNotFoundError:
print("Error: File not found.")
except PermissionError:
print("Error: Permission denied.")
except Exception as e:
print("An unexpected error occurred:",
e)
6. Single Inheritance — Person and Student
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print(f"Name: {[Link]}, Age:
{[Link]}")
class Student(Person):
def __init__(self, name, age, marks):
super().__init__(name, age)
[Link] = marks
def result(self):
if [Link] >= 40:
print(f"{[Link]} has PASSED
with {[Link]} marks.")
else:
print(f"{[Link]} has FAILED
with {[Link]} marks.")
s1 = Student("Anita", 20, 65)
[Link]()
[Link]()
7. Area of a Triangle (Heron's Formula)
a, b, c = 50, 75, 100
s = (a + b + c) / 2 # semi-perimeter
area = (s * (s - a) * (s - b) * (s - c)) **
0.5
print(f"The area of the triangle is
{area:.2f} sq. m")
8. Fahrenheit to Celsius Converter
fahrenheit = float(input("Enter temperature
in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5 / 9
print(f"{fahrenheit}°F is equal to
{celsius:.2f}°C")
9. Factorial of a Number
def factorial(n):
if n < 0:
return None
result = 1
for i in range(1, n + 1):
result *= i
return result
num = int(input("Enter a number: "))
fact = factorial(num)
if fact is None:
print("Factorial not defined for
negative numbers.")
else:
print(f"Factorial of {num} is {fact}")
10. Count Characters Without String Functions
text = input("Enter a string: ")
count = 0
for ch in text:
count = count + 1
print("Number of characters:", count)
(Uses a manual loop instead of len() or other built-
in string functions.)
11. List, Dictionary, Set Operations
# (a) Remove duplicates and sort a list
numbers = [5, 2, 8, 2, 5, 1, 9, 8]
unique_sorted = sorted(set(numbers))
print("Unique sorted list:", unique_sorted)
# (b) Dictionary of student grades
students = {"Amit": 82, "Bhavna": 68,
"Chetan": 91, "Divya": 55}
print("Students scoring above 75%:")
for name, grade in [Link]():
if grade > 75:
print(name, "-", grade)
# (c) Set operations
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
print("Union:", set_a | set_b)
print("Intersection:", set_a & set_b)
print("Difference (A-B):", set_a - set_b)
12. Section A/B Roll Number Count
roll_numbers = [101, 102, 103, 104, 105,
106, 107, 108]
section_a = 0 # even
section_b = 0 # odd
for roll in roll_numbers:
if roll % 2 == 0:
section_a += 1
else:
section_b += 1
print("Section A (even roll numbers):",
section_a)
print("Section B (odd roll numbers):",
section_b)
13. Python Modules
A module is a file containing Python code (functions,
classes, variables) that can be imported and reused in
other programs, promoting organization and
reusability.
Types of modules:
1. Built-in modules: Come pre-installed with Python
(e.g., math , os , random , sys ).
import math
print([Link](16)) # 4.0
2. User-defined modules: Created by the
programmer as .py files and imported.
# [Link]
def greet(name):
return f"Hello, {name}!"
# [Link]
import mymodule
print([Link]("Akshay"))
3. Third-party/external modules: Installed via pip
(e.g., numpy , pandas , requests ).
import requests
14. Student Management Class
class Student:
def __init__(self, name, age, grade):
[Link] = name
[Link] = age
[Link] = grade
def display(self):
print(f"Name: {[Link]}, Age:
{[Link]}, Grade: {[Link]}")
student1 = Student("Riya", 16, "10th")
student2 = Student("Karan", 17, "11th")
[Link]()
[Link]()
15. Calculator with Inheritance
class Calculator:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
class Operations(Calculator):
def add(self):
return self.num1 + self.num2
def subtract(self):
return self.num1 - self.num2
def multiply(self):
return self.num1 * self.num2
def divide(self):
if self.num2 != 0:
return self.num1 / self.num2
return "Cannot divide by zero"
calc = Operations(20, 5)
print("Addition:", [Link]())
print("Subtraction:", [Link]())
print("Multiplication:", [Link]())
print("Division:", [Link]())
16. Linear Search for Roll Number
roll_numbers = [101, 105, 110, 115, 120,
125]
target = int(input("Enter roll number to
search: "))
found = False
for index in range(len(roll_numbers)):
if roll_numbers[index] == target:
print(f"Roll number {target} found
at position {index + 1}")
found = True
break
if not found:
print(f"Roll number {target} not found
in the list")
Analysis (Linear Search): The algorithm checks each
element in the list sequentially, starting from the first,
comparing it with the target value. If a match is found,
the search stops and returns the position. If the loop
completes without a match, the element is not in the
list. This has a time complexity of O(n) in the worst
case, since it may need to check every element.
17. Student Marks — Highest, Lowest, Average
n = int(input("Enter number of students:
"))
marks = []
for i in range(n):
m = float(input(f"Enter marks of
student {i+1}: "))
[Link](m)
print("All marks entered:", marks)
print("Highest mark:", max(marks))
print("Lowest mark:", min(marks))
print("Average marks:", sum(marks) /
len(marks))