Python mid sem
SECTION A - Quick Concepts (1 mark each) Set 1 Questions Q1. Which function displays output on the screen? Answer: print()Logic: Think "print" = show on screen, like printing on paper Q2. Syntax to declare a list with 10, 20, 30? Answer: numbers = [1...

SECTION A - Quick Concepts (1 mark each)
Set 1 Questions
Q1. Which function displays output on the screen?
Answer: print()
Logic: Think "print" = show on screen, like printing on paper
Q2. Syntax to declare a list with 10, 20, 30?
Answer: numbers = [10, 20, 30]
Logic: Lists use square brackets [] - think of it as a "box" holding items
Q3. Difference between == and is?
Answer:
==checks if VALUES are same (like comparing what's written on two papers)ischecks if it's the SAME OBJECT in memory (like checking if two papers are actually the same physical paper)
Example:
a = [1,2,3]
b = [1,2,3]
a == b # True (same content)
a is b # False (different objects in memory)
Q4. Keyword to define a function?
Answer: def
Logic: "def" = "define" a function
Q5. Output of print(type({1,2,3}))?
Answer: <class 'set'>
Logic: Curly braces {} with comma-separated values = set (unique items, no duplicates)
Q6. Difference between mutable and immutable?
Answer:
Mutable = Can change (list, dict, set) - think "mutable" = "modifiable"
Immutable = Cannot change (tuple, str, int, float) - think "immutable" = "permanent"
Q7. Error in if x=5: print('Hello')?
Answer: Use == not =
Logic:
=is for assignment (giving a value)==is for comparison (checking if equal)
Set 2 Questions
Q1. Function to find string length?
Answer: len()
Logic: "len" = "length"
Q2. Syntax to create dictionary with name and age?
Answer: student = {"name": "Alice", "age": 20}
Logic: Dictionary uses curly braces with key: value pairs
Q3. Difference between break and continue?
Answer:
break= Exit the entire loop (break out completely)continue= Skip current iteration, continue with next (skip one, keep going)
Q4. Module for mathematical operations?
Answer: math
Logic: Import with import math, then use math.sqrt(), math.sin(), etc.
Q5. Output of x = "123" then print(x*2)?
Answer: 123123
Logic: String multiplication repeats the string
Q6. Difference between local and global variables?
Answer:
Local = Inside function only (dies when function ends)
Global = Outside function, accessible everywhere (lives throughout program)
Q7. Error in for i in range(5) print(i)?
Answer: Missing colon :
Logic: All control structures (if, for, while) need colon at end
📖 SECTION B - Detailed Problems (5 marks each)
Set 1 - Q8: Lists vs Tuples
Key Differences:
| Feature | List | Tuple |
| Syntax | [1,2,3] | (1,2,3) |
| Mutable? | Yes ✓ | No ✗ |
| Speed | Slower | Faster |
| Use Case | Data that changes | Data that's fixed |
Logic:
Lists = Shopping list (can add/remove items)
Tuples = Birth date (never changes)
Example:
my_list = [1,2,3]
my_list[0] = 10 # Works! ✓
my_tuple = (1,2,3)
my_tuple[0] = 10 # Error! ✗
Set 1 - Q9: Prime Number Checker
Logic (Step by step):
Prime must be > 1
Only divisible by 1 and itself
Check divisors from 2 to √n (optimization: no need to check beyond square root)
Program:
num = int(input("Enter number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print('Not prime')
break
else: # else runs if loop completes without break
print('Prime')
else:
print('Not prime')
Why √n? If n = 36, factors are: 1×36, 2×18, 3×12, 4×9, 6×6. After 6, it's just reversed pairs!
Set 1 - Q10: Fibonacci Function
Logic: Each number = sum of previous two (0, 1, 1, 2, 3, 5, 8...)
Program:
def fibonacci(n):
fib = [0, 1] # Start with first two
while len(fib) < n:
fib.append(fib[-1] + fib[-2]) # Add last two
return fib[:n] # Return first n numbers
print(fibonacci(7))
# Output: [0, 1, 1, 2, 3, 5, 8]
Memory Trick: Fibonacci = "Fee-bo-nah-chee" sounds like counting in a fancy way!
Set 1 - Q11: BankAccount Class
Logic: Class = Blueprint for objects (like a form), Object = Filled form
Program:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance # Constructor sets initial state
def deposit(self, amt):
self.balance += amt
print('Deposited:', amt)
def withdraw(self, amt):
if amt <= self.balance:
self.balance -= amt
print('Withdrawn:', amt)
else:
print('Insufficient balance')
def display(self):
print('Balance:', self.balance)
# Driver code
acc = BankAccount(1000)
acc.deposit(500) # Balance: 1500
acc.withdraw(200) # Balance: 1300
acc.display() # Shows: 1300
Key Concept: self = "this specific account" (not all accounts)
Set 1 - Q12: Word Frequency Counter
Logic: Dictionary stores word as key, count as value
Program:
word_count = {}
with open('sample.txt') as f:
for line in f:
for word in line.split():
word = word.lower().strip('.,!?') # Clean word
word_count[word] = word_count.get(word, 0) + 1
print(word_count)
How it works:
.get(word, 0)returns count if exists, else 0Add 1 each time word appears
Result:
{'hello': 3, 'world': 2, ...}
Set 1 - Q13: Second Largest Number
Logic: Track two variables: first (largest) and second (second largest)
Program:
numbers = [12, 45, 7, 34, 45, 23]
first = second = float('-inf') # Start with smallest possible
for num in numbers:
if num > first:
second = first # Old first becomes second
first = num # New first
elif num > second and num != first:
second = num # Update second only
print('Second Largest:', second)
# Output: 34
Visual:
[12, 45, 7, 34, 45, 23]
↓ ↓ ↓
12→ 45(skip, duplicate)→ 34(second!)
Set 2 - Q8: For vs While Loops
Key Difference:
for= Know how many times (count-based)while= Don't know, depends on condition (condition-based)
Examples:
# FOR: Print 0 to 4 (know it's 5 times)
for i in range(5):
print(i)
# WHILE: Print until user says "stop"
while input("Continue? ") != "stop":
print("Running...")
Memory: FOR = "FORward with fixed steps", WHILE = "WHILE condition is true"
Set 2 - Q9: Palindrome Checker
Logic: Word reads same forwards and backwards (like "mom", "racecar")
Program:
s = input('Enter a string: ')
if s == s[::-1]: # Reverse with slicing
print('Palindrome')
else:
print('Not Palindrome')
Slicing Trick: [::-1] means start:end:step, where step=-1 reverses
Set 2 - Q10: Factorial Using Recursion
Logic: n! = n × (n-1)!
Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
Program:
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n-1) # Recursive call
print(factorial(5))
# Output: 120
How it works:
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120
Set 2 - Q11: Student Class with Average
Logic: Class stores student data, method calculates average
Program:
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks # List of marks
def average(self):
return sum(self.marks) / len(self.marks)
s1 = Student('Rahul', [85, 90, 95])
print('Name:', s1.name)
print('Average:', s1.average())
# Output: Name: Rahul, Average: 90.0
Key: sum() adds all, len() counts items
Set 2 - Q12: Sum Numbers from File
Logic: Read file line by line, convert to int, add to total
Program:
total = 0
with open('numbers.txt', 'r') as f:
for line in f:
total += int(line.strip()) # strip() removes \n
print('Sum:', total)
Why with? Automatically closes file (good practice!)
Set 2 - Q13: Remove Duplicates Without set()
Logic: Check if item already in new list before adding
Program:
numbers = [1, 2, 3, 2, 4, 3, 5, 1, 6]
unique = []
for num in numbers:
if num not in unique: # Not seen before?
unique.append(num) # Add it!
print('Without duplicates:', unique)
# Output: [1, 2, 3, 4, 5, 6]
Alternative (using set): unique = list(set(numbers)) (but question says don't use set!)
Quick Revision Tips
Mutable vs Immutable (Most Asked!)
Mutable (Can Change): list, dict, set
Immutable (Cannot Change): tuple, str, int, float, bool
File Handling Pattern
with open('file.txt', 'r') as f: # 'r'=read, 'w'=write
content = f.read()
Class Structure
class ClassName:
def __init__(self, params): # Constructor
self.attribute = params
def method(self): # Method
return something
Common Errors to Avoid
Forgetting colon
:after if/for/while/defUsing
=instead of==for comparisonIndentation errors (Python is strict!)
Forgetting
selfin class methods
Last-Minute Checklist
[ ]
print()for output,input()for input[ ] Lists use
[], tuples use(), sets use{}, dicts use{key: value}[ ]
==checks value,ischecks identity[ ]
breakexits loop,continueskips iteration[ ] Files opened with
withauto-close[ ]
selfrefers to current object in classes[ ] Recursion needs base case to stop
[ ]
[::-1]reverses strings/lists
Good luck with your exam! 🚀