Python Programming (BCC302) - Solutions
BTECH SEM III Examination 2025-26
SECTION A - Short Answer Questions (2 marks each)
Q.1(a) Python Variables and Numeric Data Types
Variables are named containers that store values in memory.
Example:
age = 25 # Integer
salary = 50000.50 # Float
gpa = 3.8 # Float
count = 10 # Integer
Numeric data types: int, float, complex
int: whole numbers (25, -10, 0)
float: decimal numbers (3.14, 2.5)
complex: complex numbers (3+4j)
Q.1(b) For Loop vs While Loop
For Loop While Loop
Iterates fixed number of times using Iterates until condition
range() becomes false
Syntax: for i in range(5): Syntax: while condition:
Used when iterations known
Used when iterations unknown
beforehand
Auto-increments with range() Manual increment needed
Example:
For: for i in range(5): print(i) → prints 0,1,2,3,4
While: i=0; while i<5: print(i); i+=1 → same output
Q.1(c) String Slicing
String slicing extracts portion of string using syntax: string[start:end:step]
Example:
text = "Python"
print(text[0:3]) # "Pyt" (index 0 to 2)
print(text[2:5]) # "tho" (index 2 to 4)
print(text[::2]) # "Pto" (every 2nd character)
print(text[::-1]) # "nohtyP" (reverse)
Indices: P(0) y(1) t(2) h(3) o(4) n(5)
Q.1(d) Tuple vs List
Tuple List
Immutable - cannot modify after Mutable - can add/remove/modify
creation elements
Syntax: (1, 2, 3) Syntax: [1, 2, 3]
Faster & memory efficient Slower but flexible
Safe for dictionary keys Cannot use as dict keys
Example: t = (1, 2, 3) Example: l = [1, 2, 3]
Q.1(e) Dictionary Definition and Manipulation
Dictionary is unordered collection of key-value pairs.
Definition & Example:
student = {
"name": "Raj",
"roll": 101,
"marks": 85
}
Manipulation
student["name"] = "Ajay" # Modify
student["age"] = 20 # Add new
del student["marks"] # Delete
print([Link]()) # Get all keys
Q.1(f) read() and readline() Functions
read(): Reads entire file content at once as single string
content = [Link]() # Returns complete content
readline(): Reads one line at a time, returns string with newline
line = [Link]() # Returns first line only
Difference: read() loads all → memory heavy; readline() efficient for large files
Q.1(g) Encapsulation in OOP
Encapsulation hides internal implementation details using access modifiers.
class Bank:
def init(self):
self._balance = 1000 # Protected (single underscore)
self.__pin = 1234 # Private (double underscore)
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
Benefits: Data security, controlled access, prevents direct modification
SECTION B - Medium Answer Questions (7 marks each) -
Attempt Any 3
Q.2(a) Operators, Data Types & Even-Odd Program
Operators: Arithmetic (+, -, *, /), Comparison (==, !=, <, >), Logical (and, or, not)
Data Types: int, float, str, list, tuple, dict, set
Program:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Explanation: Modulus (%) returns remainder; if remainder is 0, number is even
Q.2(b) Loop Manipulation & Prime Numbers
Loop statements:
pass: Does nothing, used as placeholder
continue: Skips current iteration, goes to next
break: Exits loop immediately
Program - Prime Numbers 1 to 50:
for num in range(1, 51):
if num < 2:
continue
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Q.2(c) String Operations & Vowel Counting
String operations: concatenation (+), slicing, repetition (*), methods (upper(), lower(),
split())
Program:
text = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print(f"Total vowels: {count}")
Using built-in:
vowel_count = sum(1 for char in text if [Link]() in "aeiou")
Q.2(d) List & Dictionary Built-in Functions & Merge
List functions: append(), extend(), insert(), remove(), pop(), sort()
Dictionary functions: keys(), values(), items(), get(), update(), pop()
Merge Two Dictionaries:
dict1 = {"name": "Raj", "age": 20}
dict2 = {"city": "Delhi", "marks": 85}
Method 1 - update()
[Link](dict2)
print(dict1)
Method 2 - merge operator (Python 3.9+)
merged = dict1 | dict2
Method 3 - unpacking
merged = {**dict1, **dict2}
Output: {'name': 'Raj', 'age': 20, 'city':
'Delhi', 'marks': 85}
Q.2(e) File Writing Functions & Student Records
write(): Writes string to file, returns number of characters written
writelines(): Writes list of strings without adding newlines automatically
Program:
Write student records
students = [
"Roll: 101, Name: Raj, Marks: 85\n",
"Roll: 102, Name: Priya, Marks: 90\n",
"Roll: 103, Name: Amit, Marks: 78\n"
]
with open("[Link]", "w") as file:
[Link](students)
Read and display
with open("[Link]", "r") as file:
print([Link]())
SECTION C - Long Answer Questions (7 marks each)
Q.3(a) Conditional Statements & Student Grading
Python blocks: Code within if/else executed conditionally
Conditional statements: if, elif, else
Program - Grade Students:
marks = int(input("Enter marks: "))
if marks >= 90:
grade = "A"
elif marks >= 80:
grade = "B"
elif marks >= 70:
grade = "C"
elif marks >= 60:
grade = "D"
else:
grade = "F"
print(f"Marks: {marks}, Grade: {grade}")
Q.3(b) For Loops & Sum Elements
For loops with strings/lists: Iterate through each character/element
Program - Sum List Elements:
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # Output: 150
Using built-in
sum_result = sum(numbers)
Q.4(a) Functions & Circle Area
Functions: Reusable blocks of code that perform specific tasks
Syntax: def function_name(parameters):
Program - Circle Area:
import math
def circle_area(radius):
"""Calculate area of circle"""
if radius < 0:
return "Radius cannot be negative"
return [Link] * radius ** 2
Usage
r = float(input("Enter radius: "))
area = circle_area(r)
print(f"Area of circle with radius {r}: {area:.2f}")
Formula: A = πr²
Q.4(b) String Manipulation & Character Replacement
String manipulation methods: replace(), upper(), lower(), split(), strip(), find()
Program - Replace Characters:
text = "Python is amazing"
Replace specific character
new_text = [Link]("a", "@")
print(new_text) # "Python is @m@zing"
Replace multiple
new_text = [Link]("is", "was")
print(new_text) # "Python was amazing"
Using loop
text = "hello"
char_map = {"h": "H", "o": "O"}
result = ""
for char in text:
result += char_map.get(char, char)
print(result) # "HellO"
Q.5(a) Sets & Set Difference
Sets: Unordered collection of unique elements
Set operations: union (|), intersection (&), difference (-), symmetric_difference (^)
Program - Set Difference:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
Method 1 - difference() function
diff = [Link](set2)
print(diff) # {1, 2, 3}
Method 2 - subtraction operator
diff = set1 - set2
print(diff) # {1, 2, 3}
Explanation: Elements in set1 but not in
set2
Q.5(b) Tuple & List Slicing, Reverse Tuple
Tuple/List slicing: Extract portion using indices [start🔚step]
Program - Reverse Tuple:
my_tuple = (10, 20, 30, 40, 50)
Method 1 - slicing
reversed_tuple = my_tuple[::-1]
print(reversed_tuple) # (50, 40, 30, 20, 10)
Method 2 - reversed() function
reversed_tuple = tuple(reversed(my_tuple))
Method 3 - loop
result = ()
for i in range(len(my_tuple)-1, -1, -1):
result += (my_tuple[i],)
print(result) # (50, 40, 30, 20, 10)
Q.6(a) File Pointer seek() & Read Last N Lines
seek(): Moves file pointer to specific position (0=start, 1=current, 2=end)
Program - Read Last N Lines:
def read_last_n_lines(filename, n):
"""Read last n lines from file"""
with open(filename, "r") as file:
lines = [Link]()
return lines[-n:] if n <= len(lines) else lines
Usage
last_5 = read_last_n_lines("[Link]", 5)
for line in last_5:
print([Link]())
Alternative using seek()
def read_last_n_efficient(filename, n):
with open(filename, "rb") as file:
[Link](0, 2) # Go to end
buffer_size = 1024
lines = []
while len(lines) < n:
[Link](-buffer_size, 1)
lines = [Link]()
Q.6(b) Regular Expressions & Find Digits
Regular expressions: Pattern matching using re module
Syntax: [Link](pattern, string)
Program - Find All Digits:
import re
text = "My phone is 9876543210 and email is abc123@[Link]"
Method 1 - findall()
digits = [Link](r"\d", text)
print(digits) # ['9', '8', '7', ..., '1', '0']
print(''.join(digits)) # 9876543210
Method 2 - findall with groups
numbers = [Link](r"\d+", text)
print(numbers) # ['9876543210', '123']
Common patterns:
\d - single digit
\d+ - one or more digits
\D - non-digit
[0-9] - digit range
Q.7(a) Inheritance & Polymorphism - Multiple Inheritance
Inheritance: Class inherits properties from parent class
Polymorphism: Objects respond to same method differently
Program - Multiple Inheritance:
Parent classes
class Person:
def init(self, name):
[Link] = name
def display(self):
print(f"Name: {[Link]}")
class Student:
def init(self, roll):
[Link] = roll
def show(self):
print(f"Roll: {[Link]}")
Multiple inheritance
class Scholar(Person, Student):
def init(self, name, roll, gpa):
[Link](self, name)
[Link](self, roll)
[Link] = gpa
def details(self):
[Link]()
[Link]()
print(f"GPA: {[Link]}")
Usage
s = Scholar("Raj", 101, 3.8)
[Link]()
Output:
Name: Raj
Roll: 101
GPA: 3.8
MRO (Method Resolution Order)
print([Link])
Q.7(b) Tkinter Widgets & Simple Window with Label
Tkinter: Python's standard GUI library
Widgets: Building blocks (Label, Button, Entry, etc.)
Program - Simple Window with Label:
import tkinter as tk
from tkinter import Label, Button
Create main window
root = [Link]()
[Link]("My Application")
[Link]("400x300")
Create label
label = Label(root, text="Welcome to Python GUI",
font=("Arial", 14, "bold"),
fg="blue")
[Link](pady=20)
Create another label with information
info = Label(root, text="This is a simple Tkinter window",
font=("Arial", 10))
[Link]()
Create button
def on_click():
[Link](text="Button Clicked!")
btn = Button(root, text="Click Me", command=on_click,
bg="green", fg="white")
[Link](pady=10)
Run window
[Link]()
Output: Window with welcome message and clickable button
Summary
This exam covers fundamental Python concepts:
Section A: Basic concepts (variables, loops, strings, data structures, files, OOP)
Section B: Problem-solving with operators, loops, strings, and files
Section C: Complex programming using functions, advanced data structures, file
handling, regex, and GUI
Key Focus Areas:
Master control flow (if-elif-else, loops)
Understand data structures (lists, tuples, dictionaries, sets)
File I/O operations
String manipulation and regex
Object-Oriented Programming concepts
Tkinter for GUI development