0% found this document useful (0 votes)
4 views30 pages

Python Final Exam

The document is an exam guide for Python programming covering key concepts such as Python basics, data types, operators, conditional statements, and loops. It outlines an exam pattern with five sections and provides detailed explanations, examples, and outputs for various Python programming topics. The guide emphasizes the importance of indentation, variable assignment, and type conversion in Python.

Uploaded by

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

Python Final Exam

The document is an exam guide for Python programming covering key concepts such as Python basics, data types, operators, conditional statements, and loops. It outlines an exam pattern with five sections and provides detailed explanations, examples, and outputs for various Python programming topics. The guide emphasizes the importance of indentation, variable assignment, and type conversion in Python.

Uploaded by

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

PYTHON PROGRAMMING

BCA-DSC-4(Min)-405 | Complete Theory + Code + Output Exam Guide

EXAM PATTERN — 5 SECTIONS

Section A: Unit I | Section B: Unit II | Section C: Unit III

Section D: Unit IV | Section E: Compulsory Short Questions

3 Long Questions per Section | Full Theory + Clean Code + Output


SECTION – A (UNIT I)
Python Basics • Data Types • Operators • Variables • Type Conversion • if/elif/else • Loops • Strings

Q1. What is Python Programming? Explain its features, data types, variables,
operators and type conversion in detail with examples. ★ HIGH PRIORITY
Answer:
1. Introduction to Python
Python is a high-level, interpreted, general-purpose programming language. It was created by Guido
van Rossum and first released in 1991. The name "Python" came from a British comedy show called
"Monty Python's Flying Circus" that Guido van Rossum enjoyed. Python has grown to become one of
the most popular programming languages in the world. It is used in Web Development, Data Science,
Artificial Intelligence, Machine Learning, Automation, Game Development, and Scientific Research.
Python is especially loved by beginners because its syntax is very close to plain English — making it
easy to read and understand.

2. Features of Python
• Simple and Readable Syntax: Python code reads almost like English sentences. There are no curly
braces {} or semicolons. Indentation is used to define code blocks. This makes Python very clean
and easy to understand even for beginners.
• Interpreted Language: Python does not need to be compiled before running. The Python interpreter
reads and executes the code line by line directly. This makes testing and debugging very fast — you
see errors immediately.
• Dynamically Typed: In Python you do NOT need to declare the type of a variable. Python
automatically figures out the type from the value you assign. For example: x = 10 (Python knows x is
an integer automatically).
• Free and Open Source: Python is completely free to download and use. The source code of Python
is available to everyone. Anyone can contribute to improving Python.
• Platform Independent / Portable: Python code written on Windows runs without any changes on
Linux or Mac. This is called "Write Once Run Anywhere."
• Large Standard Library: Python comes with hundreds of built-in modules like math, os, random,
datetime, json — so you don't have to write everything from scratch.
• Supports Multiple Programming Paradigms: Python supports Object-Oriented Programming
(classes), Procedural Programming (functions), and Functional Programming (map, filter, lambda).
• Extensible: You can write Python code that calls C or C++ programs. This is useful for
performance-critical tasks.

3. Variables in Python
A variable is a named storage location in memory that holds a value. Think of a variable like a labelled
box — the label is the variable name and what is inside the box is the value. In Python, you do not
declare a variable — you just assign a value to it and Python creates it automatically. Variables can
store different types of data — numbers, text, lists, etc.

Rules for naming variables:


• Must start with a letter (a-z, A-Z) or underscore (_)
• Cannot start with a digit (0-9)
• Cannot contain spaces — use underscore instead (my_name, not my name)
• Cannot use Python keywords like if, for, while, class, def, etc.
• Variable names are case-sensitive — Age and age are two different variables

# Variable Assignment name = "Raj" # str type age = 20 # int type marks = 98.5 #
float type passed = True # bool type city = None # NoneType # Multiple Assignment
in one line x = y = z = 0 # all three get value 0 a, b, c = 10, 20, 30 # a=10,
b=20, c=30 # Printing variables print(name) # Raj print(age) # 20
print(type(marks)) # # Swapping two variables (very easy in Python) x, y = 5, 10 x,
y = y, x # swap! print(x, y) # 10 5
Output:
Raj 20 10 5

4. Data Types in Python


Data type defines what kind of value a variable holds and what operations can be performed on it.
Python has the following built-in data types:

Data Type Keyword Example Description

Integer int x = 10 Whole numbers, positive or negative, no decimal

Float float x = 3.14 Numbers with decimal point

String str x = "Hello" Sequence of characters, in quotes

Boolean bool x = True Only two values: True or False

List list x = [1,2,3] Ordered, mutable collection

Tuple tuple x = (1,2,3) Ordered, immutable collection

Dictionary dict x = {"a":1} Key-value pairs

Set set x = {1,2,3} Unordered, unique elements

NoneType None x = None Represents no value / null

# Demonstrating Data Types a = 100 # int b = 3.14 # float c = "Python" # str d =


True # bool e = [1, 2, 3] # list f = (10, 20) # tuple g = {"key": "val"} # dict h =
{1, 2, 3} # set print(type(a)) # print(type(b)) # print(type(c)) # print(type(d))
# print(type(e)) #
Output:

5. Operators in Python
Operators are special symbols that perform operations on values/variables. Python has several
categories of operators:

Category Operators Example Result

Arithmetic + - * / // % ** 10 // 3 and 10 % 3 3 and 1


Comparison == != > < >= <= 5 == 5 and 5 != 3 True and True

Logical and or not True and False False

Assignment = += -= *= /= x=5; x+=3 x becomes 8

Identity is is not x is None True/False

Membership in not in "a" in "cat" True

# Arithmetic Operators a, b = 17, 5 print(a + b) # Addition = 22 print(a - b) #


Subtraction = 12 print(a * b) # Multiplication = 85 print(a / b) # Division = 3.4
print(a // b) # Floor Division = 3 (removes decimal) print(a % b) # Modulus = 2
(remainder) print(a ** b) # Power = 1419857 # Logical Operators age, income = 25,
50000 print(age >= 18 and income >= 30000) # True print(age < 18 or income >=
30000) # True print(not (age < 18)) # True
Output:
22 12 85 3.4 3 2 1419857 True True True

6. Type Conversion in Python


Type conversion means changing a value from one data type to another. This is also called "Type
Casting." There are two types of type conversion in Python:

• Implicit Type Conversion (Automatic): Python automatically converts a smaller data type to a
larger data type to avoid data loss. For example, when you add an int to a float, Python
automatically converts the int to float before performing the addition.
• Explicit Type Conversion (Manual): The programmer manually converts one type to another using
built-in conversion functions like int(), float(), str(), etc.
# Implicit Type Conversion num_int = 10 # int num_float = 2.5 # float result =
num_int + num_float # Python auto converts int to float print(result) # 12.5
print(type(result)) # # Explicit Type Conversion # int() — converts to integer
print(int("42")) # 42 (string to int) print(int(3.99)) # 3 (float to int,
truncates) print(int(True)) # 1 (bool to int) # float() — converts to float
print(float("3.14")) # 3.14 print(float(10)) # 10.0 # str() — converts to string
print(str(100)) # "100" print(str(3.14)) # "3.14" print(str(True)) # "True" #
bool() — converts to boolean print(bool(0)) # False print(bool(1)) # True
print(bool("")) # False (empty string = False) print(bool("hello")) # True
(non-empty = True) print(bool([])) # False (empty list = False) # list() and
tuple() print(list("abc")) # ['a', 'b', 'c'] print(tuple([1, 2, 3])) # (1, 2, 3)
Output:
12.5 42 3 1 3.14 10.0 "100" "3.14" "True" False True False True False ['a', 'b',
'c'] (1, 2, 3)

Note: type() function is used to check the data type of any variable. Always use int(input()) when you
expect the user to enter a number, because input() always returns a string.

Conclusion: Python's simple variable system, rich set of data types, and easy type conversion make it
extremely programmer-friendly. Understanding these basics is the foundation of everything in Python.

Q2. Explain Conditional Statements in Python: simple if, if-else, if-elif-else, and
nested if. Explain the concept of indentation. Give real-world examples for each. ★
HIGH PRIORITY
Answer:
1. Introduction
In real life, we constantly make decisions: "If it is raining, I will carry an umbrella, otherwise I will not."
Computer programs also need to make decisions. Conditional statements allow a program to choose
between different actions based on whether a condition is True or False. This is what makes a program
intelligent — it can behave differently in different situations. In Python, conditions are written using the
keywords: if, elif, and else.

2. The Concept of Indentation


Indentation is one of the most important concepts in Python. Unlike other languages that use curly
braces {} to define code blocks, Python uses whitespace (spaces/tabs) at the beginning of a line. All
statements that belong to the same block must have the same indentation. The standard is 4 spaces. If
indentation is wrong, Python gives an IndentationError and the program does not run.

# CORRECT indentation if True: print("Line 1") # 4 spaces indent print("Line 2") #


same 4 spaces — same block print("Outside") # no indent — outside the if block #
WRONG — causes IndentationError # if True: # print("Error!") # no indent — Python
rejects this

3. Simple if Statement
The simple if statement executes a block of code ONLY when its condition is True. If the condition is
False, the block is completely skipped and the program moves to the next statement after the if block.
The condition is followed by a colon (:) and the code block is indented.

Syntax:

if condition: # this block runs only if condition is True statement1 statement2

Example — Check if a student passed:


marks = int(input("Enter your marks: ")) if marks >= 35: print("Congratulations!")
print("You have passed the exam.") print("Keep it up!") print("Thank you for using
the system.")
Output:
Enter your marks: 50 Congratulations! You have passed the exam. Keep it up! Thank
you for using the system.

4. if-else Statement
The if-else statement gives two paths. If the condition is True, the if block runs. If the condition is False,
the else block runs. Exactly ONE of the two blocks always executes. The else keyword has no condition
— it handles everything the if did not handle.

age = int(input("Enter your age: ")) if age >= 18: print("You are an adult.")
print("You are eligible to vote.") else: print("You are a minor.") print("You
cannot vote yet.") print("Thank you!")
Output (when age = 20):
Enter your age: 20 You are an adult. You are eligible to vote. Thank you!

Output (when age = 15):


Enter your age: 15 You are a minor. You cannot vote yet. Thank you!
5. if-elif-else Statement
When there are more than two possible outcomes, we use elif (short for "else if"). Python checks the
conditions one by one from top to bottom. The very first condition that is True — its block executes and
all the remaining elif and else blocks are skipped. The else at the end is optional — it handles all cases
not covered by if/elif.

marks = int(input("Enter marks (0 to 100): ")) if marks >= 75: grade =


"Distinction" message = "Excellent performance!" elif marks >= 60: grade = "First
Class" message = "Very good!" elif marks >= 50: grade = "Second Class" message =
"Good job!" elif marks >= 35: grade = "Pass" message = "You passed!" else: grade =
"Fail" message = "Better luck next time." print(f"Grade : {grade}") print(f"Remark
: {message}")
Output (when marks = 82):
Enter marks (0 to 100): 82 Grade : Distinction Remark : Excellent performance!

Output (when marks = 28):


Enter marks (0 to 100): 28 Grade : Fail Remark : Better luck next time.

6. Nested if Statement
A nested if is an if statement written inside another if statement. The inner if is checked only when the
outer if condition is True. Nested ifs are used when a decision depends on another decision. Be careful
with indentation in nested ifs.

username = input("Enter username: ") password = input("Enter password: ") if


username == "admin": print("Username correct!") if password == "1234":
print("Password correct!") print("Login successful. Welcome, Admin!") else:
print("Wrong password! Access denied.") else: print("Username not found! Access
denied.")
Output (correct credentials):
Enter username: admin Enter password: 1234 Username correct! Password correct!
Login successful. Welcome, Admin!

Output (wrong password):


Enter username: admin Enter password: wrong Username correct! Wrong password!
Access denied.

7. Comparison Table
Statement When to Use Blocks that Execute

if One possible action if block only (or nothing)

if-else Two possible actions Either if OR else

if-elif-else Multiple possible actions First matching block only

Nested if Decision inside a decision Inner block depends on outer


Conclusion: Conditional statements give programs the power to make decisions. The if-elif-else
structure handles multiple outcomes cleanly and efficiently. Always remember the colon (:) at the end of
each condition and proper indentation inside each block.
Q3. Explain for loop and while loop in Python with all variations. Cover range(),
break, continue, nested loops, and loop with strings and lists. Give detailed
examples with output for each. ★ HIGH PRIORITY
Answer:
1. Introduction to Loops
A loop is a control structure that repeats a block of code multiple times. Loops are one of the most
important concepts in programming because they save us from writing the same code repeatedly. For
example, if you want to print numbers 1 to 100, without a loop you would need 100 print statements.
With a loop, you need just 2 lines. Python has two main types of loops: the for loop and the while loop.

2. The for Loop


The for loop is used when you know exactly how many times to repeat, or when you want to iterate (go
through) each element of a sequence such as a list, string, tuple, or range. The loop variable
automatically takes the value of each element one by one.

Using range() with for loop:

The range() function generates a sequence of numbers. range(stop) — from 0 to stop-1. range(start,
stop) — from start to stop-1. range(start, stop, step) — from start to stop-1 with given step.

# range(stop) — starts at 0 for i in range(5): print(i, end=" ") # Output: 0 1 2 3


4 # range(start, stop) for i in range(1, 6): print(i, end=" ") # Output: 1 2 3 4 5
# range(start, stop, step) for i in range(0, 20, 4): print(i, end=" ") # Output: 0
4 8 12 16 # Countdown using negative step for i in range(10, 0, -2): print(i, end="
") # Output: 10 8 6 4 2
Output:
0 1 2 3 4 1 2 3 4 5 0 4 8 12 16 10 8 6 4 2

for loop with Strings:


# Iterate over each character of a string name = "Python" for ch in name: print(ch,
end=" ") print() # newline # Count vowels in a string word = "Programming" vowels =
"aeiouAEIOU" count = 0 for ch in word: if ch in vowels: count += 1 print(f"Vowels
in '{word}': {count}")
Output:
P y t h o n Vowels in 'Programming': 3

for loop with Lists:

# Basic list iteration fruits = ["Apple", "Mango", "Banana", "Orange"] for fruit
in fruits: print("Fruit:", fruit) print() # Using enumerate() to get index and
value together for index, fruit in enumerate(fruits): print(f" [{index}] ->
{fruit}") print() # Calculate total and average using for loop marks = [78, 92, 55,
88, 65] total = 0 for m in marks: total += m average = total / len(marks)
print(f"Total : {total}") print(f"Average : {average}")
Output:
Fruit: Apple Fruit: Mango Fruit: Banana Fruit: Orange [0] -> Apple [1] -> Mango [2]
-> Banana [3] -> Orange Total : 378 Average : 75.6

3. The while Loop


The while loop repeats a block of code as long as its condition remains True. It is used when you do
NOT know in advance how many times to repeat — the loop continues until some condition becomes
False. IMPORTANT: You must update the loop variable inside the while loop, otherwise the condition
never becomes False and you get an infinite loop that runs forever and crashes the program.

# Basic while loop — print 1 to 5 i = 1 while i <= 5: print(f"Count: {i}") i += 1 #


VERY IMPORTANT — update i each time print("Loop finished!")
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop finished!

# while loop with user input — keep asking until correct secret = 42 attempts = 0
while True: guess = int(input("Guess the number (1-100): ")) attempts += 1 if
guess < secret: print("Too low! Try higher.") elif guess > secret: print("Too
high! Try lower.") else: print(f"Correct! You got it in {attempts} attempt(s)!")
break # exit the loop when correct
Output:
Guess the number (1-100): 20 Too low! Try higher. Guess the number (1-100): 60 Too
high! Try lower. Guess the number (1-100): 42 Correct! You got it in 3 attempt(s)!

4. break and continue Statements


break — immediately exits the loop, even if the condition is still True. The program continues from the
first line after the loop.

continue — skips the rest of the current iteration and jumps back to the top of the loop to check the
condition again.

# break example — find first even number print("Finding first even number after
10:") for i in range(11, 25): if i % 2 == 0: print(f"Found: {i}") break print(f"
{i} is odd, skipping...") print() # continue example — print only odd numbers
print("Odd numbers from 1 to 10:") for i in range(1, 11): if i % 2 == 0: continue #
skip even numbers print(i, end=" ")
Output:
Finding first even number after 10: 11 is odd, skipping... Found: 12 Odd numbers
from 1 to 10: 1 3 5 7 9

5. Nested Loops
A loop inside another loop is called a nested loop. For each single iteration of the outer loop, the inner
loop completes ALL of its iterations from start to finish. Nested loops are commonly used for patterns,
multiplication tables, and matrices.

# Multiplication table using nested loop print("Multiplication Table (1 to 5):")


print("-" * 35) for i in range(1, 6): # outer loop — row for j in range(1, 6): #
inner loop — column print(f"{i*j:4}", end="") print() # newline after each row
print("-" * 35) # Star triangle pattern n = 5 for i in range(1, n + 1): for j in
range(i): # j runs i times print("*", end=" ") print()
Output:
Multiplication Table (1 to 5): ----------------------------------- 1 2 3 4 5 2 4 6 8
10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 ----------------------------------- * * *
* * * * * * * * * * * *

Loop Type Best Used When Key Requirement


for loop Number of iterations known in advance A sequence or range to iterate over

while loop Condition-based, iterations unknown Condition that eventually becomes False

Nested loop Working with tables, patterns, matrices Careful indentation for both loops
Conclusion: Loops are the heart of every program that does repetitive work. The for loop is clean and
readable for known iterations. The while loop handles unknown iterations based on conditions. break
and continue give fine control inside loops.
SECTION – B (UNIT II)
Lists • Tuples • Dictionaries — Theory, Operations, Methods, Traversal, Mutable vs Immutable

Q4. What are Lists in Python? Explain its definition, operations, all important
methods, traversal, nested lists, and mutable nature with complete examples and
output. ★ HIGH PRIORITY
Answer:
1. Definition and Introduction
A List is an ordered, mutable collection that can hold multiple values of any data type — all in a single
variable. Lists are created using square brackets [] and elements are separated by commas. Lists are
the most widely used data structure in Python. They are ordered — meaning elements maintain the
order in which they were inserted. They are mutable — meaning you can change, add, or remove
elements after creation. Lists allow duplicate values. List index starts at 0 from the left and at -1 from the
right end.

# Different ways to create a list empty_list = [] # empty list numbers = [10, 20,
30, 40, 50] # integer list names = ["Raj", "Priya", "Amit"] # string list mixed =
[1, "hello", 3.14, True] # mixed types nested = [1, [2, 3], [4, 5, 6]] # nested
list # Using list() constructor chars = list("Python") # ['P','y','t','h','o','n']
print(chars) print(len(numbers)) # 5 — number of elements
Output:
['P', 'y', 't', 'h', 'o', 'n'] 5

2. Indexing and Slicing


Each element in a list has a position number called an index. Python supports both positive indexing
(left to right, starts at 0) and negative indexing (right to left, starts at -1). Slicing extracts a portion of the
list using the syntax: list[start:stop:step]. The start is included but stop is NOT included.
lst = [10, 20, 30, 40, 50, 60, 70] # 0 1 2 3 4 5 6 <- positive index # -7 -6 -5 -4
-3 -2 -1 <- negative index # Positive indexing print(lst[0]) # 10 — first element
print(lst[3]) # 40 — fourth element print(lst[6]) # 70 — last element # Negative
indexing print(lst[-1]) # 70 — last element print(lst[-3]) # 50 — third from end #
Slicing — lst[start:stop:step] print(lst[1:5]) # [20, 30, 40, 50] — index 1 to 4
print(lst[:4]) # [10, 20, 30, 40] — from start to index 3 print(lst[3:]) # [40, 50,
60, 70] — from index 3 to end print(lst[::2]) # [10, 30, 50, 70] — every 2nd
element print(lst[::-1]) # [70,60,50,40,30,20,10] — reversed list
Output:
10 40 70 70 50 [20, 30, 40, 50] [10, 20, 30, 40] [40, 50, 60, 70] [10, 30, 50, 70]
[70, 60, 50, 40, 30, 20, 10]

3. List Methods
Method Purpose Example Result

append(x) Add x at end [Link](80) [10,20,...,80]

insert(i,x) Insert x at index i [Link](2,99) [10,20,99,30..]

remove(x) Remove first occurrence [Link](30) removes 30


pop() Remove & return last [Link]() returns 70

pop(i) Remove at index i [Link](0) removes 10

sort() Sort ascending (in-place) [Link]() [10,20,30..]

sort(reverse=True) Sort descending [Link](reverse=True) [70,60..]

reverse() Reverse the list [Link]() [70,60..10]

index(x) Index of first x [Link](30) 2

count(x) Count occurrences of x [Link](20) 1

extend(lst2) Add all items from lst2 [Link]([8,9]) merged

copy() Return a copy b = [Link]() new list

clear() Remove all elements [Link]() []

len(lst) Number of elements len(lst) 7

lst = [40, 10, 30, 20, 50] [Link](60) print("After append(60) :", lst)
[Link](2, 99) print("After insert(2,99):", lst) [Link](99) print("After
remove(99) :", lst) popped = [Link]() print("Popped element :", popped)
print("After pop() :", lst) [Link]() print("After sort() :", lst) [Link]()
print("After reverse() :", lst) print("Index of 40 :", [Link](40)) print("Count
of 10 :", [Link](10))
Output:
After append(60) : [40, 10, 30, 20, 50, 60] After insert(2,99): [40, 10, 99, 30, 20,
50, 60] After remove(99) : [40, 10, 30, 20, 50, 60] Popped element : 60 After pop()
: [40, 10, 30, 20, 50] After sort() : [10, 20, 30, 40, 50] After reverse() : [50,
40, 30, 20, 10] Index of 40 : 1 Count of 10 : 1

4. List Traversal
students = ["Raj", "Priya", "Amit", "Sara"] # Method 1 — for-in (most common and
cleanest) print("Method 1: for-in loop") for student in students: print(" ",
student) # Method 2 — using range and index print("Method 2: index-based") for i in
range(len(students)): print(f" [{i}] {students[i]}") # Method 3 — enumerate() for
index + value print("Method 3: enumerate") for idx, name in enumerate(students,
start=1): print(f" Student {idx}: {name}") # Method 4 — while loop print("Method
4: while loop") i = 0 while i < len(students): print(" ", students[i]) i += 1
Output:
Method 1: for-in loop Raj Priya Amit Sara Method 2: index-based [0] Raj [1] Priya
[2] Amit [3] Sara Method 3: enumerate Student 1: Raj Student 2: Priya Student 3:
Amit Student 4: Sara Method 4: while loop Raj Priya Amit Sara

5. Nested Lists (2D List / Matrix)


A nested list is a list that contains other lists as its elements. This is used to represent two-dimensional
data like tables and matrices. To access an element: list[row_index][column_index].

# 3x3 matrix using nested list matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] #
Accessing elements print(matrix[0]) # [1, 2, 3] — first row print(matrix[1][2]) #
6 — row 1, col 2 print(matrix[2][0]) # 7 — row 2, col 0 # Print full matrix row by
row print("\nMatrix:") for row in matrix: for item in row: print(f"{item:4}",
end="") print() # Sum of all elements total = 0 for row in matrix: for item in row:
total += item print(f"Sum of all elements: {total}")
Output:
[1, 2, 3] 6 7 Matrix: 1 2 3 4 5 6 7 8 9 Sum of all elements: 45

Conclusion: Lists are the backbone of Python data manipulation. Their mutable nature, rich set of
methods, and support for nesting make them powerful enough to handle most real-world data storage
needs.

Q5. What are Tuples in Python? Explain creation, operations, methods,


packing/unpacking, traversal, nested tuples, and compare tuples with lists. ★ HIGH
PRIORITY
Answer:
1. Definition and Introduction
A Tuple is an ordered, immutable collection of elements. "Ordered" means elements maintain the
position they were inserted in. "Immutable" means once a tuple is created, you CANNOT change, add,
or remove elements. This is the biggest difference from a list. Tuples are created using parentheses ()
with elements separated by commas. Tuples are faster than lists, use less memory, and are safer for
data that should not change — like days of the week, months, or database records.

# Creating tuples t1 = (10, 20, 30, 40, 50) # basic tuple t2 = ("Raj", 20, 78.5,
True) # mixed types allowed t3 = () # empty tuple t4 = (99,) # single element —
comma is REQUIRED! t5 = 1, 2, 3, 4 # parentheses optional (packing) print(t1) #
(10, 20, 30, 40, 50) print(type(t4)) # print(len(t1)) # 5 # WRONG — single element
without comma is NOT a tuple wrong = (99) # this is just int 99 with brackets!
print(type(wrong)) #
Output:
(10, 20, 30, 40, 50) 5

2. Accessing Elements — Indexing and Slicing


Tuple indexing works exactly like lists — positive index from 0, negative index from -1. Slicing also
works the same way.
t = (10, 20, 30, 40, 50, 60) # Indexing print(t[0]) # 10 — first print(t[-1]) # 60
— last print(t[2]) # 30 # Slicing print(t[1:4]) # (20, 30, 40) print(t[:3]) # (10,
20, 30) print(t[::-1]) # (60, 50, 40, 30, 20, 10) reversed # Immutability — cannot
change elements # t[0] = 999 # TypeError: tuple does not support item assignment
Output:
10 60 30 (20, 30, 40) (10, 20, 30) (60, 50, 40, 30, 20, 10)

3. Tuple Methods and Operations


Tuples have only two built-in methods because they are immutable. However, other useful operations
like len(), max(), min(), sum(), and in work with tuples.

t = (10, 30, 20, 10, 40, 10, 20) # Methods print([Link](10)) # 3 — count
occurrences of 10 print([Link](20)) # 2 — index of first occurrence of 20 # Other
useful operations print(len(t)) # 7 — number of elements print(max(t)) # 40 —
maximum value print(min(t)) # 10 — minimum value print(sum(t)) # 140 — sum of all
elements # Membership check print(30 in t) # True print(99 in t) # False #
Concatenation and Repetition a = (1, 2, 3) b = (4, 5, 6) print(a + b) # (1, 2, 3,
4, 5, 6) print(a * 3) # (1,2,3,1,2,3,1,2,3) # Convert between list and tuple
my_list = list(t) # tuple to list my_tuple = tuple([1,2,3]) # list to tuple
print(my_tuple) # (1, 2, 3)
Output:
3 2 7 40 10 140 True False (1, 2, 3, 4, 5, 6) (1, 2, 3, 1, 2, 3, 1, 2, 3) (1, 2, 3)

4. Tuple Packing and Unpacking


Packing means combining multiple values into a single tuple. Unpacking means assigning each element
of a tuple to separate variables. The number of variables must match the number of elements in the
tuple.

# Packing — values grouped into tuple automatically coordinates = 10, 20, 30 # same
as (10, 20, 30) print(coordinates) # (10, 20, 30) # Unpacking — each value assigned
to a variable x, y, z = coordinates print(f"x={x}, y={y}, z={z}") # x=10, y=20,
z=30 # Swap variables using tuple unpacking (Python trick) a, b = 100, 200 a, b =
b, a # swap in one line! print(f"a={a}, b={b}") # a=200, b=100 # Function returning
multiple values (uses tuple) def get_student_info(): name = "Raj" age = 20 marks =
78 return name, age, marks # returns as tuple n, a, m = get_student_info() # unpack
returned tuple print(f"Name: {n}, Age: {a}, Marks: {m}")
Output:
(10, 20, 30) x=10, y=20, z=30 a=200, b=100 Name: Raj, Age: 20, Marks: 78

5. Nested Tuples
# Student records stored as nested tuple students = ( (101, "Raj", 78), (102,
"Priya", 92), (103, "Amit", 55), (104, "Sara", 88), ) print(f"%-8s %-12s %-8s %s"
% ("Roll","Name","Marks","Grade")) print("-" * 38) for student in students: roll,
name, marks = student # unpack each record if marks >= 75: grade = "Distinction"
elif marks >= 35: grade = "Pass" else: grade = "Fail" print(f"{roll:<8} {name:<12}
{marks:<8} {grade}")
Output:
Roll Name Marks Grade -------------------------------------- 101 Raj 78 Pass 102
Priya 92 Distinction 103 Amit 55 Pass 104 Sara 88 Distinction

6. List vs Tuple — Comparison


Feature List Tuple

Syntax [ ] square brackets ( ) parentheses

Mutable? YES — can modify NO — cannot modify

Speed Slower Faster (Python optimized)

Memory Usage More Less

Methods 14+ methods available Only count() and index()

Dictionary Key? NO (mutable=unhashable) YES (immutable=hashable)

Iteration Same — for-in works Same — for-in works

When to use Data that changes Fixed/constant data


Example Shopping cart, scores Coordinates, months
Conclusion: Tuples are perfect for data that should remain constant. They are faster and safer than
lists. Use tuples for things like coordinates, configurations, and function return values.

Q6. What is a Dictionary in Python? Explain its creation, operations, all methods,
traversal, nested dictionaries, and manipulation with examples. ★ HIGH PRIORITY
Answer:
1. Definition and Introduction
A Dictionary is an unordered collection of KEY-VALUE pairs. It is created using curly braces {} with each
entry written as key: value. Dictionaries are like a real-world dictionary — you look up a word (key) and
get its meaning (value). Keys must be unique and immutable (strings, numbers, tuples). Values can be
of any data type and can be duplicated. Dictionaries are the most powerful built-in data structure for
organizing and retrieving labeled data quickly.

# Creating dictionaries student = {"name": "Raj", "age": 20, "marks": 78, "city":
"Delhi"} empty = {} # empty dictionary # Using dict() constructor info =
dict(name="Priya", age=21, marks=92) # Keys can be int too roll_db = {101: "Raj",
102: "Priya", 103: "Amit"} print(student) print(info) print(len(student)) # 4 —
number of key-value pairs
Output:
{'name': 'Raj', 'age': 20, 'marks': 78, 'city': 'Delhi'} {'name': 'Priya', 'age':
21, 'marks': 92} 4

2. Accessing, Adding, Updating, Deleting


student = {"name": "Raj", "age": 20, "marks": 78} # Accessing values
print(student["name"]) # Raj print([Link]("age")) # 20
print([Link]("city")) # None (no error if missing)
print([Link]("city","N/A"))# N/A (default value) # Adding new key-value pair
student["email"] = "raj@[Link]" print("After adding email:", student) #
Updating an existing value student["marks"] = 85 print("After updating marks:",
student["marks"]) # Deleting a key-value pair del student["email"] print("After
deleting email:", student) # pop() — remove and return value removed_age =
[Link]("age") print("Removed age value:", removed_age) print("Dictionary
now:", student)
Output:
Raj 20 None N/A After adding email: {'name': 'Raj', 'age': 20, 'marks': 78, 'email':
'raj@[Link]'} After updating marks: 85 After deleting email: {'name': 'Raj',
'age': 20, 'marks': 85} Removed age value: 20 Dictionary now: {'name': 'Raj',
'marks': 85}

3. Dictionary Methods
Method Purpose Returns

[Link]() All keys dict_keys(['name','age'])

[Link]() All values dict_values(['Raj', 20])

[Link]() All (key,value) pairs dict_items([('name','Raj')])


[Link](k) Value of key k (safe) Value or None

[Link](k, def) Value or default Value or def

[Link](k) Remove key k, return val Removed value

[Link](d2) Add/update with d2 None (modifies d)

[Link]() Shallow copy New dict

[Link]() Remove all pairs None, dict becomes {}

k in d Check if key exists True or False

4. Dictionary Traversal (All Methods)


subject_marks = { "Maths": 85, "English": 72, "Science": 90, "Hindi": 68 } #
Method 1 — traverse keys only print("Subjects:") for subject in subject_marks:
print(" ", subject) # Method 2 — traverse values only print("\nMarks:") for score
in subject_marks.values(): print(" ", score) # Method 3 — traverse key-value pairs
(most useful) print("\nSubject-wise Report:") for subject, score in
subject_marks.items(): status = "Pass" if score >= 35 else "Fail" print(f"
{subject:<10}: {score} ({status})") # Calculate total total =
sum(subject_marks.values()) print(f"\nTotal Marks : {total}") print(f"Percentage :
{total/4:.1f}%")
Output:
Subjects: Maths English Science Hindi Marks: 85 72 90 68 Subject-wise Report: Maths
: 85 (Pass) English : 72 (Pass) Science : 90 (Pass) Hindi : 68 (Pass) Total Marks :
315 Percentage : 78.8%

5. Nested Dictionary
# Student database using nested dictionary database = { 101: {"name": "Raj",
"marks": 78, "city": "Delhi"}, 102: {"name": "Priya", "marks": 92, "city":
"Mumbai"}, 103: {"name": "Amit", "marks": 55, "city": "Chennai"}, } # Accessing
nested values print(database[101]["name"]) # Raj print(database[102]["marks"]) #
92 # Adding a new student record database[104] = {"name": "Sara", "marks": 88,
"city": "Kolkata"} # Display all records print("\n=== Student Database ===") for
roll, info in [Link](): print(f"Roll {roll}: {info['name']} | Marks:
{info['marks']} | City: {info['city']}")
Output:
Raj 92 === Student Database === Roll 101: Raj | Marks: 78 | City: Delhi Roll 102:
Priya | Marks: 92 | City: Mumbai Roll 103: Amit | Marks: 55 | City: Chennai Roll
104: Sara | Marks: 88 | City: Kolkata

Conclusion: Dictionaries are ideal for storing structured, labeled data where fast retrieval by key is
needed. They are used extensively in real-world applications — JSON data, configuration files,
databases, and API responses all use dictionary-like structure.
SECTION – C (UNIT III)
Functions — Arguments, Return Values, *args, Standard Libraries • Classes — OOP, __init__, self,
Inheritance • Strings

Q7. What is a Function in Python? Explain user-defined functions, all types of


arguments, return statement, *args, **kwargs, passing a list, and Python standard
libraries in detail. ★ HIGH PRIORITY
Answer:
1. Introduction to Functions
A function is a named, reusable block of code that performs a specific task. Instead of writing the same
code again and again in different places, we define it once as a function and simply call the function
name whenever we need it. This follows the programming principle of "Don't Repeat Yourself" (DRY).
Functions make programs shorter, more organized, easier to understand, easier to test, and easier to fix
(when there is a bug, you fix it in one place).

There are two types of functions in Python:

• Built-in Functions: Already provided by Python — print(), len(), int(), max(), min(), sum(), range(),
type(), input(), etc.
• User-defined Functions: Functions you create yourself using the def keyword.

2. Defining and Calling a Function


Syntax: def function_name(parameters): — followed by an indented block. The function is only
DEFINED here — it does NOT run yet. To actually run the function, you must CALL it by writing its
name followed by parentheses.

# Defining a function def greet(): print("=" * 30) print(" Hello! Welcome to


Python!") print("=" * 30) # Calling the function — runs every time you call it
greet() # First call greet() # Second call — same code runs again!
Output:
============================== Hello! Welcome to Python!
============================== ============================== Hello! Welcome to
Python! ==============================

3. Types of Function Arguments


(a) Positional Arguments — Order matters:

def student_info(name, roll, marks): print(f"Name : {name}") print(f"Roll :


{roll}") print(f"Marks : {marks}") print("-" * 25) student_info("Raj", 101, 78) #
name="Raj", roll=101, marks=78 student_info("Priya", 102, 92) # order must match
the definition
Output:
Name : Raj Roll : 101 Marks : 78 ------------------------- Name : Priya Roll : 102
Marks : 92 -------------------------

(b) Default Arguments — Used when caller does not pass a value:

def greet(name, message="Hello", punctuation="!"): print(f"{message},


{name}{punctuation}") greet("Raj") # uses both defaults greet("Priya", "Hi") #
overrides message greet("Amit", "Good Morning", ".") # overrides both
Output:
Hello, Raj! Hi, Priya! Good Morning, Amit.

(c) Keyword Arguments — Pass by name, order does not matter:

def register(name, age, city): print(f"{name} | Age: {age} | City: {city}") #


Normal call register("Raj", 20, "Delhi") # Keyword call — any order
register(city="Mumbai", name="Priya", age=21) # Mix — positional first, then
keyword register("Amit", city="Chennai", age=22)
Output:
Raj | Age: 20 | City: Delhi Priya | Age: 21 | City: Mumbai Amit | Age: 22 | City:
Chennai

(d) *args — Any number of positional arguments (received as tuple):

def calculate_total(*amounts): print(f"Arguments received: {amounts}")


print(f"Type: {type(amounts)}") total = 0 for amount in amounts: total += amount
return total print("Total:", calculate_total(100, 200, 300)) print("Total:",
calculate_total(50, 75, 25, 100, 200))
Output:
Arguments received: (100, 200, 300) Type: Total: 600 Arguments received: (50, 75,
25, 100, 200) Type: Total: 450

(e) **kwargs — Any number of keyword arguments (received as dict):

def display_profile(**details): print("=== Profile ===") for key, value in


[Link](): print(f" {key:<12}: {value}") print("=" * 18)
display_profile(name="Raj", age=20, city="Delhi", hobby="Reading")
display_profile(name="Priya", marks=92, subject="Maths")
Output:
=== Profile === name : Raj age : 20 city : Delhi hobby : Reading ==================
=== Profile === name : Priya marks : 92 subject : Maths ==================

4. Return Statement
The return statement sends a value back from the function to the caller. A function can return any data
type — int, float, string, list, tuple, etc. If no return is used, the function returns None automatically. A
function can also return multiple values — Python packages them as a tuple.

def bmi_calculator(weight_kg, height_m): bmi = weight_kg / (height_m ** 2) if bmi


< 18.5: category = "Underweight" elif bmi < 25.0: category = "Normal weight" elif
bmi < 30.0: category = "Overweight" else: category = "Obese" return round(bmi, 2),
category # return TWO values bmi_value, bmi_cat = bmi_calculator(70, 1.75)
print(f"BMI : {bmi_value}") print(f"Category : {bmi_cat}")
Output:
BMI : 22.86 Category : Normal weight

5. Passing a List to a Function


def add_bonus(marks_list, bonus): """Adds bonus marks — modifies original list
(pass by reference)""" for i in range(len(marks_list)): marks_list[i] += bonus def
get_statistics(marks_list): """Returns summary statistics""" n = len(marks_list)
total = sum(marks_list) avg = total / n high = max(marks_list) low =
min(marks_list) return total, avg, high, low scores = [45, 67, 80, 55, 72]
print("Before bonus:", scores) add_bonus(scores, 5) # original list is modified!
print("After bonus :", scores) t, a, h, l = get_statistics(scores) print(f"Total:
{t} | Average: {a:.1f} | High: {h} | Low: {l}")
Output:
Before bonus: [45, 67, 80, 55, 72] After bonus : [50, 72, 85, 60, 77] Total: 344 |
Average: 68.8 | High: 85 | Low: 50

6. Python Standard Libraries


# math module import math print([Link](144)) # 12.0 print([Link]) #
3.141592653589793 print([Link](3.9)) # 3 print([Link](3.1)) # 4
print([Link](5)) # 120 # random module import random
print([Link](1, 10)) # random int between 1 and 10 print([Link]())
# float between 0.0 and 1.0 print([Link](["A","B","C"])) # random choice
from list lst = [1, 2, 3, 4, 5] [Link](lst) # shuffle list in-place
print(lst) # os module import os print([Link]()) # current working directory #
from keyword for specific import from math import sqrt, pi print(sqrt(81)) # 9.0 —
no need for [Link]
Output:
12.0 3.141592653589793 3 4 120 7 (random example) 0.6543... (random float) A
(random choice) [3, 1, 5, 2, 4] (shuffled) /home/user/documents 9.0

Conclusion: Functions are the most important tool for code organization. Mastering all types of
arguments — especially *args and **kwargs — gives you the power to write flexible, professional-grade
functions.

Q8. What are Classes and Objects in Python? Explain __init__, self, instance
variables, class variables, methods, and inheritance in detail. ★ HIGH PRIORITY
Answer:
1. Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a way of structuring programs around "objects" rather than
functions and logic alone. An object is a real-world entity that has attributes (data/properties) and
behaviors (actions/methods). For example: A "Student" object has attributes like name, roll number,
marks and behaviors like display_info(), calculate_grade(). In Python, a CLASS is the blueprint or
template that describes what attributes and methods an object will have. An OBJECT is an actual
instance (created copy) of that class.

Real World Class (Blueprint) Object (Instance)

Manufacturing Car blueprint/design Your actual car

Baking Cookie cutter shape Individual cookie

College Student form/template Raj's filled form

Mobile app Contact template Each saved contact

2. Creating a Class and Understanding __init__ and self


class keyword is used to define a class. Class name should start with a capital letter (convention).
__init__ is the constructor method — it is called automatically every time you create a new object. It
sets up the initial state (instance variables) of the object. self is a reference to the current object being
used. It must be the first parameter in every method. Through self, each object can access its own data.

class BankAccount: # Class variable — shared by ALL objects bank_name = "Python


National Bank" interest_rate = 4.5 # Constructor — called when object is created
def __init__(self, owner, account_no, balance=0): # Instance variables — unique to
each object [Link] = owner self.account_no = account_no [Link] = balance
def deposit(self, amount): if amount > 0: [Link] += amount print(f"
Deposited Rs.{amount}. New Balance: Rs.{[Link]}") else: print(" Invalid
amount!") def withdraw(self, amount): if amount > [Link]: print("
Insufficient balance!") else: [Link] -= amount print(f" Withdrawn
Rs.{amount}. Remaining: Rs.{[Link]}") def display(self): print(f" Bank :
{BankAccount.bank_name}") print(f" Owner : {[Link]}") print(f" Account :
{self.account_no}") print(f" Balance : Rs.{[Link]}") # Create objects acc1 =
BankAccount("Raj", "ACC001", 5000) acc2 = BankAccount("Priya", "ACC002", 10000)
print("--- Raj's Account ---") [Link]() [Link](2000)
[Link](1500) print("\n--- Priya's Account ---") [Link]()
[Link](15000) # should fail
Output:
--- Raj's Account --- Bank : Python National Bank Owner : Raj Account : ACC001
Balance : Rs.5000 Deposited Rs.2000. New Balance: Rs.7000 Withdrawn Rs.1500.
Remaining: Rs.5500 --- Priya's Account --- Bank : Python National Bank Owner : Priya
Account : ACC002 Balance : Rs.10000 Insufficient balance!

3. Inheritance
Inheritance allows a child class to inherit all properties and methods from a parent class, without
rewriting the same code. The child class can also add new methods and override existing ones. This
promotes code reuse and establishes a parent-child relationship between classes. Syntax: class
ChildClass(ParentClass):
# Parent class class Person: def __init__(self, name, age): [Link] = name
[Link] = age def introduce(self): print(f" Hi! I am {[Link]}, age
{[Link]}.") def display_type(self): print(" I am a Person.") # Child class
inheriting from Person class Student(Person): def __init__(self, name, age, roll,
marks): super().__init__(name, age) # call parent __init__ [Link] = roll
[Link] = marks # New method — only in Student def study_info(self): grade =
"Pass" if [Link] >= 35 else "Fail" print(f" Roll: {[Link]} | Marks:
{[Link]} | {grade}") # Method Overriding — redefine parent method def
display_type(self): print(" I am a Student!") class Teacher(Person): def
__init__(self, name, age, subject): super().__init__(name, age) [Link] =
subject def teach(self): print(f" Teaching subject: {[Link]}") def
display_type(self): print(" I am a Teacher!") # Create objects s = Student("Raj",
20, 101, 78) t = Teacher("Mr. Sharma", 40, "Python") [Link]() # inherited
from Person s.display_type() # overridden in Student s.study_info() # only in
Student [Link]() # inherited from Person t.display_type() # overridden in
Teacher [Link]() # only in Teacher
Output:
Hi! I am Raj, age 20. I am a Student! Roll: 101 | Marks: 78 | Pass Hi! I am Mr.
Sharma, age 40. I am a Teacher! Teaching subject: Python
Conclusion: OOP with classes and objects makes programs more organized, reusable, and easier to
model real-world situations. __init__ and self are the foundation of every class. Inheritance is one of the
most powerful features of OOP.

Q9. What are Strings in Python? Explain string creation, indexing, slicing, all
important methods, traversal, and string formatting. ★★ MEDIUM PRIORITY
Answer:
1. Introduction
A String is an ordered, immutable sequence of characters. Strings can contain letters, digits, spaces,
and special characters. They are created using single quotes, double quotes, or triple quotes. Being
immutable means once created, individual characters cannot be changed — you can only create a new
string. Strings are indexed like lists — index 0 is the first character, index -1 is the last.

# Creating strings s1 = 'Single quotes' s2 = "Double quotes" s3 = """Triple quotes


can span multiple lines""" # Indexing word = "Python" print(word[0]) # P
print(word[5]) # n print(word[-1]) # n (last character) print(word[-3]) # h (third
from end) # Slicing print(word[0:3]) # Pyt print(word[2:]) # thon print(word[:4])
# Pyth print(word[::-1]) # nohtyP (reversed) # Strings are immutable # word[0] =
"J" # TypeError — cannot change!
Output:
P n n h Pyt thon Pyth nohtyP

2. String Methods
s = " Hello Python World " print([Link]()) # " HELLO PYTHON WORLD "
print([Link]()) # " hello python world " print([Link]()) # "Hello Python World"
(removes spaces) print([Link]()) # "Hello Python World " (removes left only)
print([Link]()) # " Hello Python World" (removes right only) t = "Hello Python
World" print([Link]("Python", "Java")) # "Hello Java World" print([Link](" "))
# ['Hello', 'Python', 'World'] print("-".join(["a","b","c"])) # "a-b-c"
print([Link]("Python")) # 6 (index of substring) print([Link]("l")) # 3 (count
occurrences) print([Link]("Hello"))# True print([Link]("World")) # True
print([Link]()) # "Hello Python World" (first letter caps) # Checking type
print("123".isdigit()) # True (all digits) print("abc".isalpha()) # True (all
letters) print("abc123".isalnum()) # True (letters + digits)
Output:
HELLO PYTHON WORLD hello python world Hello Python World Hello Python World Hello
Python World Hello Java World ['Hello', 'Python', 'World'] a-b-c 6 3 True True Hello
Python World True True True

3. String Traversal
sentence = "Python is Great" # Traverse character by character for ch in sentence:
print(ch, end=" ") print() # Count vowels and consonants vowels = 0 consonants = 0
for ch in [Link](): if [Link](): if ch in "aeiou": vowels += 1 else:
consonants += 1 print(f"Vowels : {vowels}") print(f"Consonants : {consonants}") #
Reverse words words = [Link]() reversed_sentence = "
".join(reversed(words)) print(f"Reversed : {reversed_sentence}")
Output:
P y t h o n i s G r e a t Vowels : 5 Consonants : 9 Reversed : Great is Python
Conclusion: Strings are immutable sequences with a rich collection of methods. Mastering slicing and
string methods is essential as they appear in almost every Python exam.
SECTION – D (UNIT IV)
Exception Handling — try/except/else/finally • File Handling — read/write/append/seek/tell

Q10. What is Exception Handling in Python? Explain try, except, else, finally in
detail. Cover all common exception types with complete examples and output. ★
HIGH PRIORITY
Answer:
1. Introduction — What is an Exception?
When Python encounters an error while executing a program, it stops immediately and shows an error
message. This is called an Exception. An exception is a runtime error — it does not appear when you
write the code, only when you run it. For example, if a user types letters when a number is expected, or
divides by zero, or tries to open a file that does not exist — Python raises an exception and the program
crashes. Exception Handling is the technique of catching these errors gracefully and handling them
without crashing the program. It makes programs robust, user-friendly, and professional.

2. The try-except Block


The try block contains code that might cause an error (risky code). The except block contains code that
runs if the error actually occurs. If NO error occurs in the try block, the except block is completely
skipped. If an error DOES occur, Python jumps immediately to the matching except block.

# Without exception handling — program crashes! # num = int("hello") # ValueError


— crash! # print(10 / 0) # ZeroDivisionError — crash! # With exception handling —
program continues try: num = int(input("Enter a number: ")) result = 100 / num
print(f"100 / {num} = {result}") except ZeroDivisionError: print("Error: Cannot
divide by zero!") except ValueError: print("Error: Please enter a valid integer!")
print("Program continues after exception handling...")
Output (when input = 5):
Enter a number: 5 100 / 5 = 20.0 Program continues after exception handling...

Output (when input = 0):


Enter a number: 0 Error: Cannot divide by zero! Program continues after exception
handling...

Output (when input = "abc"):


Enter a number: abc Error: Please enter a valid integer! Program continues after
exception handling...

3. Common Exception Types


Exception Cause Example that triggers it

ZeroDivisionError Division by zero 10 / 0

ValueError Wrong value/type int("hello")

FileNotFoundError File does not exist open("[Link]")

IndexError List index out of range lst[100]

KeyError Dict key not found d["xyz"]

TypeError Wrong operation for type "5" + 5


NameError Variable not defined print(xyz)

AttributeError Object has no attribute [Link]()

ImportError Module not found import xyz

RecursionError Infinite recursion Function calls itself endlessly

4. else and finally Blocks


else block — runs ONLY when the try block executes without any exception. It is the "success" path.

finally block — ALWAYS runs, whether an exception occurred or not. It is used for cleanup tasks like
closing files or database connections.

def divide_numbers(a, b): try: result = a / b except ZeroDivisionError: print("


Caught: Division by zero!") except TypeError: print(" Caught: Numbers must be
integers or floats!") else: # runs ONLY when try succeeds (no exception) print(f"
Success! {a} / {b} = {result:.4f}") finally: # ALWAYS runs — success or failure
print(" Operation attempt finished.") print() print("--- Test 1: Normal division
---") divide_numbers(10, 4) print("--- Test 2: Division by zero ---")
divide_numbers(10, 0) print("--- Test 3: Wrong type ---") divide_numbers(10,
"five")
Output:
--- Test 1: Normal division --- Success! 10 / 4 = 2.5000 Operation attempt finished.
--- Test 2: Division by zero --- Caught: Division by zero! Operation attempt
finished. --- Test 3: Wrong type --- Caught: Numbers must be integers or floats!
Operation attempt finished.

5. Catching Any Exception and Getting Error Details


# Using "as e" to get error message details try: numbers = [1, 2, 3]
print(numbers[10]) # IndexError except IndexError as e: print(f"IndexError : {e}")
try: result = "hello" + 5 # TypeError except TypeError as e: print(f"TypeError :
{e}") # Catch ANY exception with base Exception class try: x = int("not_a_number")
except Exception as e: print(f"Exception : {type(e).__name__}: {e}") # Multiple
exceptions in one line try: val = int(input("Enter value: ")) print(10 / val)
except (ValueError, ZeroDivisionError) as e: print(f"Handled: {type(e).__name__}:
{e}")
Output:
IndexError : list index out of range TypeError : can only concatenate str (not
"int") to str Exception : ValueError: invalid literal for int() with base 10:
'not_a_number'

6. raise Statement — Raising Exceptions Manually


def validate_age(age): if not isinstance(age, int): raise TypeError(f"Age must be
integer, got {type(age).__name__}") if age < 0: raise ValueError(f"Age cannot be
negative: {age}") if age > 150: raise ValueError(f"Age {age} is unrealistically
large") return f"Valid age: {age}" # Test the function tests = [25, -5, 200,
"twenty"] for test in tests: try: result = validate_age(test) print(f" Input
{str(test):<8}: {result}") except (TypeError, ValueError) as e: print(f" Input
{str(test):<8}: ERROR — {e}")
Output:
Input 25 : Valid age: 25 Input -5 : ERROR — Age cannot be negative: -5 Input 200 :
ERROR — Age 200 is unrealistically large Input twenty : ERROR — Age must be integer,
got str

Conclusion: Exception handling is a must-have in any real-world program. try-except separates normal
logic from error-handling logic. The else block handles success; finally always runs for cleanup. Never
let a program crash — always catch and handle exceptions gracefully.

Q11. What is File Handling in Python? Explain all file modes, reading, writing,
appending, seek(), tell(), and a complete file-based student record program with full
output. ★ HIGH PRIORITY
Answer:
1. Introduction
File Handling allows Python programs to permanently store data on the computer's hard disk and read it
back later. Without file handling, all data stored in variables is lost when the program closes. With file
handling, data persists across program runs — just like how a Word document saves your text. Python
uses the built-in open() function to work with files. The modern, recommended approach is the with
statement which automatically closes the file when the block ends.

2. File Opening Modes


Mode Full Name File Exists? File Missing? Read? Write?

"r" Read only Open at start FileNotFoundError YES NO

"w" Write (overwrite) ERASE content Create new file NO YES

"a" Append Add to end Create new file NO YES

"r+" Read + Write Open at start FileNotFoundError YES YES

"w+" Write + Read ERASE content Create new file YES YES

"a+" Append + Read Add to end Create new file YES YES

3. Writing to a File
# write() — writes a single string with open("[Link]", "w") as f: [Link]("Line
1: Python is amazing\n") [Link]("Line 2: File handling is important\n")
[Link]("Line 3: Practice makes perfect\n") print("File written successfully!") #
writelines() — writes a list of strings lines = [ "First entry\n", "Second
entry\n", "Third entry\n" ] with open("[Link]", "w") as f:
[Link](lines) print("Entries file created!")
Output:
File written successfully! Entries file created!

4. Reading from a File


# Method 1 — read() reads entire file as one string with open("[Link]", "r") as
f: content = [Link]() print("=== Full Content ===") print(content) # Method 2 —
readline() reads one line at a time with open("[Link]", "r") as f: print("===
Line by Line ===") line = [Link]() while line: print([Link]()) line =
[Link]() # Method 3 — readlines() reads all lines into a list with
open("[Link]", "r") as f: all_lines = [Link]() print(f"Total lines:
{len(all_lines)}") # Method 4 — iterate directly (best for large files) print("===
Direct Iteration ===") with open("[Link]", "r") as f: for line_num, line in
enumerate(f, start=1): print(f" Line {line_num}: {[Link]()}")
Output:
=== Full Content === Line 1: Python is amazing Line 2: File handling is important
Line 3: Practice makes perfect === Line by Line === Line 1: Python is amazing Line
2: File handling is important Line 3: Practice makes perfect Total lines: 3 ===
Direct Iteration === Line 1: Line 1: Python is amazing Line 2: Line 2: File handling
is important Line 3: Line 3: Practice makes perfect

5. Appending to a File
# "a" mode — adds to end, does NOT delete existing content with open("[Link]",
"a") as f: [Link]("Line 4: Appended line — keeps old data!\n") [Link]("Line 5:
Another appended line\n") print("Data appended!") # Verify — read the updated file
with open("[Link]", "r") as f: print([Link]())
Output:
Data appended! Line 1: Python is amazing Line 2: File handling is important Line 3:
Practice makes perfect Line 4: Appended line — keeps old data! Line 5: Another
appended line

6. seek() and tell()


tell() returns the current position (in bytes) of the file pointer. seek(offset, whence) moves the file
pointer to a specific position. whence=0 (from beginning — default), whence=1 (from current),
whence=2 (from end).

with open("[Link]", "r") as f: print("Start position:", [Link]()) # 0 first =


[Link](20) # read 20 characters print("After reading 20 chars:", [Link]())
print("Read:", first) [Link](0) # go back to beginning print("After seek(0):",
[Link]()) # 0 again [Link](0, 2) # jump to END of file size = [Link]() print(f"File
size: {size} bytes")
Output:
Start position: 0 After reading 20 chars: 20 Read: Line 1: Python is a After
seek(0): 0 File size: 147 bytes

7. Complete Student Record Program


import os FILENAME = "student_records.txt" def save_record(roll, name, marks):
"""Append one student record to file""" with open(FILENAME, "a") as f:
[Link](f"{roll},{name},{marks}\n") print(f" Saved: Roll {roll} — {name}") def
display_all(): """Read and display all records""" if not [Link](FILENAME):
print(" No records found!") return print(" %-8s %-12s %-8s %-6s" %
("Roll","Name","Marks","Grade")) print(" " + "-" * 38) with open(FILENAME, "r") as
f: for line in f: parts = [Link]().split(",") roll, name, marks = parts[0],
parts[1], int(parts[2]) grade = "A" if marks >= 75 else "B" if marks >= 50 else "C"
print(f" {roll:<8} {name:<12} {marks:<8} {grade}") # Add records print("--- Saving
Records ---") save_record(101, "Raj", 78) save_record(102, "Priya", 92)
save_record(103, "Amit", 55) print("\n--- All Records ---") display_all()
Output:
--- Saving Records --- Saved: Roll 101 — Raj Saved: Roll 102 — Priya Saved: Roll 103
— Amit --- All Records --- Roll Name Marks Grade
-------------------------------------- 101 Raj 78 B 102 Priya 92 A 103 Amit 55 B
Conclusion: File handling is essential for any application that needs to store data permanently. Always
use the with statement for safe file handling. Understand "r", "w", "a" modes thoroughly — they appear
in every exam.

Q12. Explain Exception Handling combined with File Handling. Write programs
demonstrating FileNotFoundError, creating a file, traversing a file, and using
seek/tell. ★★ MEDIUM PRIORITY
Answer:
1. Why Combine Exception Handling with File Handling?
File operations are one of the most error-prone areas in programming. Files may not exist, you may not
have permission to read them, they may be corrupted, or the disk may be full when writing. Without
exception handling, any of these situations crashes your program. With exception handling, you catch
these errors, show friendly messages, and allow the program to continue or try again. This combination
is standard practice in all professional Python programs.

2. Handling FileNotFoundError
def safe_read_file(filename): """Read a file safely with full exception
handling""" print(f"Attempting to read: '{filename}'") try: with open(filename,
"r") as f: content = [Link]() if not [Link](): print(" File exists but is
empty!") else: print(" File content:") for i, line in
enumerate([Link]("\n"), 1): if [Link](): print(f" {i}. {line}") except
FileNotFoundError: print(f" Error: File '{filename}' not found!") print(" Please
check the filename and try again.") except PermissionError: print(f" Error: No
permission to read '{filename}'") except Exception as e: print(f" Unexpected
error: {type(e).__name__}: {e}") else: print(" File read successfully!") finally:
print(" Read attempt done.\n") safe_read_file("[Link]")
safe_read_file("does_not_exist.txt")
Output:
Attempting to read: '[Link]' File content: 1. Python is amazing 2. File handling
is important File read successfully! Read attempt done. Attempting to read:
'does_not_exist.txt' Error: File 'does_not_exist.txt' not found! Please check the
filename and try again. Read attempt done.

3. Complete Program — Creating, Writing, Reading, Traversing


import os def create_and_write(filename, data_list): """Create file and write list
of lines""" try: with open(filename, "w") as f: [Link]("ID,Subject,Score\n") #
header line for row in data_list: [Link](",".join(str(x) for x in row) + "\n")
print(f"Created '{filename}' with {len(data_list)} records.") except Exception as
e: print(f"Write error: {e}") def traverse_and_analyze(filename): """Read file and
compute statistics""" try: scores = [] print(f"\n=== Reading '{filename}' ===")
with open(filename, "r") as f: header = [Link]().strip() print(f"Header :
{header}") print("-" * 30) for line in f: parts = [Link]().split(",") sid,
subject, score = parts[0], parts[1], int(parts[2]) [Link](score) grade =
"PASS" if score >= 35 else "FAIL" print(f" {sid} | {subject:<12} | {score:>3} |
{grade}") print("-" * 30) print(f"Total records : {len(scores)}") print(f"Highest
score : {max(scores)}") print(f"Lowest score : {min(scores)}") print(f"Average
score : {sum(scores)/len(scores):.1f}") except FileNotFoundError: print("File not
found! Run create_and_write() first.") except ValueError as e: print(f"Data format
error: {e}") # Data to save data = [ (1, "Maths", 85), (2, "English", 72), (3,
"Science", 90), (4, "Hindi", 28), (5, "Python", 95), ]
create_and_write("[Link]", data) traverse_and_analyze("[Link]")
Output:
Created '[Link]' with 5 records. === Reading '[Link]' === Header :
ID,Subject,Score ------------------------------ 1 | Maths | 85 | PASS 2 | English |
72 | PASS 3 | Science | 90 | PASS 4 | Hindi | 28 | FAIL 5 | Python | 95 | PASS
------------------------------ Total records : 5 Highest score : 95 Lowest score :
28 Average score : 74.0

Conclusion: Combining exception handling with file handling makes programs professional and
reliable. Always use try-except when working with files, and always use the with statement to ensure
files are closed properly.
SECTION – E (COMPULSORY)
Attempt ALL Questions | Short Answer Type | Covers Entire Syllabus

1. What is Python? State any 4 features. ■


Python is a high-level, interpreted, open-source, general-purpose programming language created by
Guido van Rossum in 1991. Features: (1) Simple and readable syntax close to English. (2)
Interpreted — runs line by line, no compilation needed. (3) Dynamically typed — no variable type
declaration required. (4) Platform independent — same code runs on Windows, Linux, Mac. (5)
Large standard library — math, os, random, datetime, etc.

2. What is the difference between List and Tuple? ■


List is created with [] and is MUTABLE (can be changed after creation). Tuple is created with () and
is IMMUTABLE (cannot be changed after creation). List is slower and uses more memory; Tuple is
faster and uses less memory. List has 14+ methods; Tuple has only count() and index(). Tuples can
be used as dictionary keys; lists cannot.

3. What is __init__ in Python classes? ■


__init__ is the constructor method of a class. It is automatically called whenever a new object is
created from the class. It is used to initialize the instance variables (attributes) of the object. Syntax:
def __init__(self, param1, param2): self.param1 = param1. self refers to the current object being
created.

4. What is the difference between 'r', 'w', and 'a' file modes? ■
'r' (Read): Opens an existing file for reading only. Raises FileNotFoundError if file does not exist. 'w'
(Write): Creates a new file or OVERWRITES an existing file completely. All previous content is
deleted. 'a' (Append): Creates a new file or adds new content to the END of an existing file without
deleting previous content.

5. What is ZeroDivisionError? How to handle it? ■


ZeroDivisionError is raised when any number is divided by zero. Example: print(10 / 0) causes
ZeroDivisionError: division by zero. Handle using try-except: try: result = 10 / 0 except
ZeroDivisionError: print('Cannot divide by zero!')

6. What is scope of a variable? Types?


Scope is the part of the program where a variable is accessible. Local scope: variable created inside
a function, accessible only within that function. Global scope: variable created outside all functions,
accessible throughout the file. Use the global keyword to modify a global variable inside a function.

7. What is the difference between append() and extend()? ■


append(x) adds x as a SINGLE element at the end. [Link]([4,5]) results in [..., [4,5]] — list inside
list. extend(iterable) unpacks and adds ALL items of the iterable one by one. [Link]([4,5]) results
in [..., 4, 5] — items added individually.
8. What is the 'with' statement in file handling? ■
The with statement is a context manager for file handling. Syntax: with open('[Link]', 'r') as f: ... It
automatically closes the file when the block ends, even if an exception occurs inside the block. This
prevents resource leaks and is the recommended way to handle files in Python.

9. What is default argument in function? ■


A default argument has a preset value that is used when the caller does not provide that argument. It
is defined by assigning a value in the function definition: def greet(name, msg='Hello'). greet('Raj')
uses default 'Hello'. greet('Raj', 'Hi') overrides the default with 'Hi'. Default arguments must come
after positional arguments.

10. What is type conversion? Types? ■


Type conversion means changing a value from one data type to another. Implicit (automatic): Python
auto-converts for compatibility — int + float gives float. Explicit (manual/casting): Programmer uses
int(), float(), str(), bool(), list(), etc. Examples: int('42') → 42, float(10) → 10.0, str(99) → '99', bool(0)
→ False.

11. What is a nested list? Give example.


A list inside another list is a nested list. Used for 2D data like tables and matrices. Example: matrix =
[[1,2,3],[4,5,6],[7,8,9]]. Access: matrix[1][2] gives 6 (row index 1, column index 2). Iterate with two for
loops: for row in matrix: for item in row: print(item).

12. Explain *args with example. ■


*args allows a function to accept any number of positional arguments. All extra arguments are
packed into a tuple. Example: def total(*nums): return sum(nums). total(1,2,3) → 6,
total(10,20,30,40) → 100. The * before the name is the key — the name 'args' is just a convention.

13. What is the finally block? ■


The finally block in exception handling ALWAYS executes — whether an exception was raised or
not. It is used for cleanup code such as closing files, releasing resources, or closing connections.
Structure: try: ... except: ... else: ... finally: print('always runs')

14. What is seek() and tell() in Python?


tell() returns the current position (in bytes) of the file pointer inside the file. seek(offset) moves the file
pointer to a specific position in the file. seek(0) moves to the beginning, seek(0,2) moves to the end.
Useful when you want to re-read a file or jump to a specific location.

15. What is inheritance in Python? ■


Inheritance allows a child class to inherit all properties and methods from a parent class without
rewriting the code. Syntax: class Child(Parent). super().__init__() is used to call the parent's
constructor. Method Overriding: child class redefines a method from parent with its own logic.
Benefit: Code reuse, easier maintenance, natural hierarchy modeling.
ALL THE BEST! YOU
BCA-DSC-4(Min)-405 | Python CAN DO IT! ■
Programming

LAST-MINUTE EXAM TIPS

Write a clear 2-3 line Introduction for every long answer

Always write Output separately below every code block

Section E is COMPULSORY — attempt it first, it takes less time

Attempt ONE question from each of Section A, B, C, D

For class questions — always write __init__ and self properly

For file handling — always mention the mode used and why

Indentation in Python code must be 4 spaces — examiners check this!

If you forget exact syntax, write the logic in simple English

You might also like