0% found this document useful (0 votes)
20 views65 pages

Python Programming Question Bank

The document is a question bank for a Python Programming course for B.Tech. students at the School of Computing for the academic year Summer 2025-26. It outlines course outcomes, unit contents, and includes a series of questions categorized by marks and difficulty levels, covering topics such as data types, control statements, functions, and error handling in Python. The document serves as a resource for students to prepare for assessments in the course.
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)
20 views65 pages

Python Programming Question Bank

The document is a question bank for a Python Programming course for B.Tech. students at the School of Computing for the academic year Summer 2025-26. It outlines course outcomes, unit contents, and includes a series of questions categorized by marks and difficulty levels, covering topics such as data types, control statements, functions, and error handling in Python. The document serves as a resource for students to prepare for assessments in the course.
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

VTR UGE 2021- (CBCS)

School of Computing
[Link]. – Computer Science and Engineering
Question Bank – Integrated Courses
Academic Year: Summer 2025 - 26
Course Category : Program Core
Course Code / Title : 10211CS213 / Python Programming
Semester : Summer 25-26
Achievable Course Outcomes
CO1 Experiment with data types, operators, statements and functions in K3
python.
CO2 Construct the file handling, string handling and regular expression K3
functions in python
CO3 Make use of the Exception handling to handle errors and multithreading K3
mechanism for parallel execution.
CO4 Demonstrate the use of python libraries for data analysis. K3
CO5 Apply python modules for Graphical User Interface and game design K3

Unit – I
Unit 1 Introduction L-3 Hours
Unit Contents:
Python Basics:variables-data types-operators and expressions- control statements-comments in the
program-python collections (List,Tuple,Set,Dictionary)- modules-packages and composition.
Python functions-built-in functions-Lambda functions- python iterator and generator.
Case Study: Shuffling a Deck of Card.

[Link] Two Marks Questions. (K1 Level Only) Course


Marks Level
Outcome
1. Clarify the guidelines for naming variables in Python with 2 CO1 K2
suitable examples.

✔ A variable name must start with a letter or the


underscore character
✔ A variable name cannot start with a number
✔ A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three
different variables)

1
2. Articulate the features of four built-in data types in Python. 2 CO1 K2
➤ Python has several built-in data types. Four common ones
are:

o int – for integers like 10


o float – for floating-point numbers like 3.14
o str – for text like "Hello"

list – for ordered sequences like [1, 2, 3]


3. Arrange variables for storing your name, age, and height, 2 CO1 K2
then display them in order with the print() function.

name = "John"
age = 25
height = 5.9

print(name, age, height)


4. Defend the need for precedence rules in evaluating Python 2 CO1 K2
expressions.
In Python, expressions are combinations of values, variables,
operators, and function calls that are evaluated to produce a
result. The order of evaluation follows Python's operator
precedence and associativity rules. Operators with higher
precedence are evaluated first, and operators with the same
precedence are evaluated based on their associativity (usually
left-to-right).
Key Points about Order of Evaluation:
1. Parentheses () have the highest precedence and are used
to group expressions.
2. Arithmetic operators follow this precedence:
o Exponentiation ** (evaluated right-to-left)
o Multiplication, Division, Modulo, Floor
Division (*, /, %, //)
o Addition and Subtraction (+, -)
3. Comparison operators (==, !=, <, >, <=, >=) are evaluated
after arithmetic operators.
4. Logical operators (and, or, not) are evaluated later:
o not has the highest precedence among logical
operators.
o and has higher precedence than or.

5. Find the area of a rectangle using variables length and 2 CO1 K2


breadth using python

length = 10

2
breadth = 5
area = length * breadth
print("Area =", area)

Expected Output:
Area = 50

6. Differentiate break and continue statement in Python. 2 CO1 K2


A break statement is used when we want to terminate the running
loop whenever any particular condition occurs. Whenever a
break statement occurs loop breaks and stops executing.
For example: If we have a variable curr=0 and in a while
loop we are incrementing it by one each time and printing it. Now
we want to stop whenever we get curr=5. So we can write a
break statement when we get curr=5.
On the other side continue statement is used when we have to
skip a particular iteration. Whenever we write continue
statement the whole code after that statement is skipped and
loop will go for next iteration.
For example: We have to print numbers form 1 to 5 but skip 3 .
So we can use a for loop which will print the number and when
i=3 we will continue.
7. Conclude the final result produced by the given code 2 CO1 K2
snippet.
lst = [1, 2, 3]
[Link](4)
lst[1] = 5
print(lst)
Expected Output:
[1, 5, 3, 4]
8. Associate the property of immutability with tuples and show 2 CO1 K2
it through an example.

Tuples are immutable, which means that once a tuple is created,


its elements cannot be changed, added, or removed. This
immutability is one of the key features that distinguishes tuples
from lists.
Example:
# Creating a tuple my_tuple = (1, 2, 3, 4)
# Attempting to modify an element
try:
my_tuple[0] = 10 # This will raise an error
except TypeError as e:
print(f"Error: {e}")

Immutable Nature: Tuples do not allow modification of their


elements, so any attempt to change a value (e.g., my_tuple[0] =
10) will raise a TypeError.
No Item Addition or Removal: Tuples do not support operations
like append() or remove() which are available for list.

3
9. Compare Module and Package in Python. 2 CO1 K2
In Python, both modules and packages organize and structure the
code but serve different purposes.
In simple terms, a module is a single file containing Python code,
whereas a package is a collection of modules that are organized
in a directory hierarchy.
10. Restate the meaning of an iterator in Python with clarity. 2 CO1 K2
➤ An iterator is an object that can be iterated (looped) upon
using the __iter__() and __next__() methods. It remembers its
state between iterations.
Example:

it = iter([1, 2, 3])
print(next(it)) # Output: 1

11. Arrange the steps to create a greet(name) function and 2 CO1 K2


display a greeting.

def greet(name):
print("Hello", name)

greet("Ravi")

12. Exemplify the use of yield in Python with a generator 2 CO1 K2


code snippet.➤ The yield statement is used in a function to
make it a generator. It pauses the function and returns a value,
resuming where it left off when next is called again.
Example:

def gen():
yield 1
yield 2

4
13. Conclude the final result of executing the given code snippet 2 CO1 K2

def my_generator(n):
i=0
while i < n:
yield i
i += 1
for i in my_generator(3):
print(i)

Expected Output:

0
1
2
14. Interpret the role of __iter__() and __next__() 2 CO1 K2
methods in an iterator.
• An iterator is an object that contains a countable number
of values.
• An iterator is an object that can be iterated upon,
meaning that you can traverse through all the values.
• Lists, tuples, dictionaries, and sets are all iterable
objects. They are iterable containers which you can get
an iterator from.
• All these objects have a iter() method which is used to
get an iterator.

15. Match the code statements with their corresponding 2 CO1 K2


outputs.
my_list = [4, 7, 0]
iterator = iter(my_list)

print(next(iterator))
print(next(iterator))

print(next(iterator))

Expected Output:

4
7
0

5
S. Five Marks Questions. (K2 and above Level) Course
Marks Level
No Outcome
1. Construct a Python program that declares variables of five 5 CO1 K3
different data types, demonstrate their usage with examples,
and apply the rules of variable naming.

Variables are containers for storing data values. In Python,


variables are created when you assign a value to them using the =
operator.
Rules for naming variables:

● Must start with a letter or underscore (_)


● Cannot start with a number
● Can contain letters, numbers, and underscores
● Case-sensitive (Age and age are different)
● Cannot be a Python keyword (e.g., if, for, True)

# Input different types of values


name = input("Enter your name: ") # String
age = int(input("Enter your age: ")) # Integer
gpa = float(input("Enter your GPA: ")) # Float

# Display values and their types


print("\n--- User Details ---")
print("Name:", name)
print("Age:", age)
print("GPA:", gpa)

print("\n--- Data Types ---")


print("Type of name:", type(name))
print("Type of age:", type(age))
print("Type of GPA:", type(gpa))

6
# Type conversion examples
print("\n--- Type Conversion ---")
print("Age as float:", float(age))
print("GPA as integer:", int(gpa))
2. Explain the difference between lists and tuples with examples. 5 CO1 K2
Write a Python program that reads a list of numbers and creates
two tuples: one with even numbers and another with odd
numbers. Explain immutability of tuple and string vs mutability
of list and dictionary with examples.

def separate_even_odd(lst):
even = tuple([x for x in lst if x % 2 == 0])
odd = tuple([x for x in lst if x % 2 != 0])
print("Even Tuple:", even)
print("Odd Tuple:", odd)

nums = list(map(int, input("Enter numbers separated by space:


").split()))
separate_even_odd(nums)

# Dictionary is mutable
my_dict = {'a': 1}
my_dict['a'] = 99
print("Dict:", my_dict)
# String is immutable
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print("String Error:", e)
# Tuple is immutable
t = (1, 2, 3)
try:

7
t[0] = 10
except TypeError as e:
print("Tuple Error:", e)
3. Interpret the syntax of the given statements in Python and 5 CO1 K2
illustrate each with an example.
i) for loop ii) while loop iii) if - else iv) if-elif-else
for Loop
The for loop iterates over a sequence (such as a list, tuple,
dictionary, set, or string) and executes a block of code for each
element in the sequence.
Syntax
for variable in iterable:
# Code to execute for each element in the iterable
Example
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
The while loop repeatedly executes a block of code as long as a
specified condition is true.
Syntax
while condition:
# Code to execute while the condition is true
Example
count = 0
while count < 5:
print("Count:", count)
count += 1
if-else Statement
The if-else statement evaluates a condition. If the condition is
true, it executes the block of code inside the if statement.
Otherwise, it executes the block of code inside the else
statement.
Syntax
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false

8
Example
number = 10
if number > 0:
print('Positive number')
else:
print('Negative number')
if…elif…else Statement
The if...else statement is used to execute a block of code among
two alternatives.
However, if we need to make a choice between more than two
alternatives, we use the if...elif...else statement.
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

4. Construct a Python program to check whether a given key is present in a 5 CO1 K3


dictionary (display the value if found, else print “Key not Found”) and
demonstrate the use of set methods (intersection(), union(),
issubset(), difference(), update(), discard()) with
examples.

# Sample dictionary
student_scores = {
"Aravind": 85,
"Bhavya": 92,
"Deepak": 76
}

# Input from user


key = input("Enter student name to check score: ")

# Check for key presence


if key in student_scores:
print(f"Score of {key}:", student_scores[key])
else:
print("Key not Found")

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

9
# a) intersection()
print("Intersection:", [Link](set2)) # {3, 4}

# b) union()
print("Union:", [Link](set2)) # {1, 2, 3, 4, 5, 6}

# c) issubset()
subset = {1, 2}
print("Is subset:", [Link](set1)) # True

# d) difference()
print("Difference (set1 - set2):", [Link](set2)) # {1, 2}

# e) update()
[Link]({7, 8})
print("After update:", set1) # {1, 2, 3, 4, 7, 8}

# f) discard()
[Link](2)
print("After discard 2:", set1) # {1, 3, 4, 7, 8}
5. Develop a Python program to calculate the final bill for a meal 5 CO1 K3
costing ₹110 with 2% tip and 8% GST, and display the amount
formatted to two decimal places.

Types of Operators in Python:

1. Arithmetic Operators: +, -, *, /, //, %, ** – Used for


mathematical calculations.
2. Relational (Comparison) Operators: ==, !=, <, >, <=, >=
– Used to compare values.
3. Logical Operators: and, or, not – Used to combine
conditional statements.
4. Assignment Operators: =, +=, -=, *=, /=, %=, etc. – Used
to assign values to variables.

# Base price of the meal


meal_price = 110.0

# Tip and GST calculations


tip = (2 / 100) * meal_price
gst = (8 / 100) * meal_price

# Total bill
total = meal_price + tip + gst

# Display the result


print("Total bill amount: ₹", round(total, 2))
6. Clarify how packages in Python contribute to modularity and 5 CO1 K2
code reuse within large applications.

A package in Python is a directory that contains multiple related


Python modules, typically organized using an __init__.py file.

10
Packages help organize code into logical, hierarchical structures
and enable better modularity, scalability, and reuse.

Benefits of using packages:

● Organizes related functionalities


● Encourages modular programming
● Supports reusability and maintainability
● Easy to navigate in large applications

Example:
def add(a, b):
return a + b
def subtract(a, b):
return a – b
def multiply(a, b):
return a * b
# This file can be left empty or used to initialize the package
from calculator import add, sub, mul

# Input from user


x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

# Using package modules


print("Addition:", [Link](x, y))
print("Subtraction:", [Link](x, y))
print("Multiplication:", [Link](x, y))
7. Discuss how to perform the read and write operation in CSV 5 CO1 K2
file using csv module and pandas library

import csv

# Module import
# List of tuples representing student data
students = [("Name", "Age", "GPA"),
("Arun", 20, 8.5),
("Bhavya", 19, 9.0),
("Chitra", 21, 8.8)]

# Writing to a CSV file


with open("[Link]", "w", newline="") as file:
writer = [Link](file)
for student in students:
[Link](student)

# Reading from a CSV file


with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)

11
import pandas as pd
# pandas is a powerful module for data analysis

# Create a DataFrame using dictionary (Python Collection)


data = {
"Name": ["Arun", "Bhavya", "Chitra"],
"Age": [20, 19, 21],
"GPA": [8.5, 9.0, 8.8]
}
df = [Link](data) # Create pandas DataFrame

# Write to CSV
df.to_csv("students_pandas.csv", index=False)

# Read from CSV


df_read = pd.read_csv("students_pandas.csv")
print(df_read)

8. A website requires the users to input username and password 5 CO1 K3


to register. Illustrate a program to check the validity of
password input by users. Following are the criteria for
checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
Your program should get password as a input and check them
according to the above criteria and print whether the given
password is accepted or not

# Password validation program

def is_valid_password(password):
# Initialize flags
has_lower = has_upper = has_digit = has_special = False
special_chars = "$#@"

# Length check
if not (6 <= len(password) <= 12):
return False

# Check each character


for ch in password:
if [Link]():
has_lower = True
elif [Link]():
has_upper = True
elif [Link]():
has_digit = True
elif ch in special_chars:
12
has_special = True

# Return True only if all conditions are met


return has_lower and has_upper and has_digit and has_special

# Taking input from user


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

# Validate and display result


if is_valid_password(password):
print("✅ Registration Successful! Password Accepted.")
else:
print("❌ Registration Failed! Invalid Password.")
9. Explain Lambda functions in Python . In a retail store 5 CO1 K2
management system, you are given a list of products with their
prices and categories. You are required to perform the
following tasks using lambda functions along with relevant
Python features like filter(), map(), and sorted(). Write a
complete Python program using appropriate data structures,
lambda functions, and built-in methods to perform these tasks.

A lambda function is an anonymous (nameless) function used


for short tasks.

It is defined using the keyword lambda.

Syntax:

lambda arguments: expression

Used with functions like filter(), map(), and sorted() for quick
operations.
# List of products (name, price, category)
products = [
("Shampoo", 120, "Personal Care"),
("Notebook", 45, "Stationery"),
("Milk", 30, "Groceries"),
("Pen", 10, "Stationery"),
("Soap", 25, "Personal Care"),
("Sugar", 50, "Groceries")
]

# 1. Filter only 'Stationery' items


stationery_items = list(filter(lambda x: x[2] ==
"Stationery", products))
print("Stationery Items:")
print(stationery_items)

# 2. Apply 10% discount on all products

13
discounted_products = list(map(lambda x: (x[0], round(x[1]
* 0.9, 2), x[2]), products))
print("\nProducts with 10% Discount:")
print(discounted_products)

# 3. Sort all products by price (after discount)


sorted_products = sorted(discounted_products, key=lambda
x: x[1])
print("\nSorted Products by Discounted Price:")
print(sorted_products)
10. Implement a Python program that declares variables of five 5 CO1 K3
different data types and displays their values along with their
data type using the type() function.

Variables are containers for storing data values. In Python,


variables are created when you assign a value to them using the =
operator.
Rules for naming variables:

● Must start with a letter or underscore (_)


● Cannot start with a number
● Can contain letters, numbers, and underscores
● Case-sensitive (Age and age are different)
● Cannot be a Python keyword (e.g., if, for, True)

# Input different types of values


name = input("Enter your name: ") # String
age = int(input("Enter your age: ")) # Integer
gpa = float(input("Enter your GPA: ")) # Float

# Display values and their types


print("\n--- User Details ---")
print("Name:", name)
print("Age:", age)
print("GPA:", gpa)

14
print("\n--- Data Types ---")
print("Type of name:", type(name))
print("Type of age:", type(age))
print("Type of GPA:", type(gpa))
# Type conversion examples
print("\n--- Type Conversion ---")
print("Age as float:", float(age))
print("GPA as integer:", int(gpa))

Unit – II
Unit 2 File Manipulation, String Handling and Regular Express L-3Hours
Unit Contents:
Manipulating files and directories, os and sys modules; text files: reading/writing text
and binary files; creating and reading a formatted file (csv or tab-separated); String
manipulations: indexing, slicing a string-string operations-number system-Regular
expressions- match and search functions; modifiers and patterns-python Decorators.
Case Studies: Creating a Hash File (or a message digest of a file) and pattern recognition.

[Link] Two Mark Questions. Course


Marks Level
Outcome
1. Differentiate [Link]() and [Link](). 2 CO2 K2

Feature [Link]() [Link]()


Deletes an empty
Function Deletes a file
directory
Empty directories
Applicable To Files only
only
Error if Used Folder (raises Non-empty directory
On IsADirectoryError) (raises OSError)
Syntax
[Link]('[Link]') [Link]('folder')
Example
2. Generalize the difference between text and binary data storage. 2 CO2 K2
Text File:
A text file stores data in human-readable format using characters
and encodings like ASCII or UTF-8. Example: .txt, .csv.
Binary File:
A binary file stores data in machine-readable format using bytes.
It may include images, audio, video, or executable files. Example:
.jpg, .exe, .mp3.
3. Recall the syntax to open a file in write mode and write text to it. 2 CO2 K2

with open('[Link]', 'w') as file:


[Link]('Your text here')

15
where 'w' mode creates the file if it doesn't exist and overwrites if
it does.
4. Conclude why CSV files are widely used and how Python 2 CO2 K2
handles them.
A CSV (Comma-Separated Values) file is a plain text file that
stores tabular data, where each line represents a row and values are
separated by commas. It is commonly used for data exchange
between applications like Excel and databases.
reading a CSV file:
import csv
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)

Explanation:
● import csv: Imports the CSV module.
● open('[Link]', 'r'): Opens the file in read mode.
● [Link](file): Reads the file using the csv reader.
● for row in reader: Iterates through each row in the file.
print(row): Prints each row as a list of values.
5. Estimate the output when slicing a string to get its first five 2 CO2 K2
characters.
my_string = "Welcome"
substring = my_string[:5]
print(substring)

6. Clarify the working of negative indexing in Python by showing 2 CO2 K2


an example.
Negative Indexing in Python allows access to elements from the
end of a sequence. The index -1 refers to the last element, -2 to
the second last, and so on.
Example:
my_list = ['a', 'b', 'c', 'd', 'e']
print(my_list[-1]) # Output: 'e'
print(my_list[-3]) # Output: 'c'
7. Demonstrate how to split a sentence into words and rejoin them 2 CO2 K2
with hyphens.
Example:
sentence = "Python is a powerful language"
words = [Link]() # Splits the sentence into a list of words
hyphen_sentence = '-'.join(words) # Joins the words with hyphens
print(hyphen_sentence)

16
8. Defend your answer for the output of the given program. 2 CO2 K2
s = "Hello"
print (s [: -1])

Output:
Hell
9. Estimate the decimal values of the list ['0b1011', 2 CO2 K2
'0o17', '0xA'].
nums = ['0b1011', '0o17', '0xA']
decimals = []
for n in nums:
if [Link]('0b'):
[Link](int(n, 2))
[Link]('0o'):
[Link](int(n, 8))
[Link]('0x'):
[Link](int(n, 16))
print(decimals) # Output: [11, 15, 10]
10. Distinguish between [Link]() and [Link]() function 2 CO2 K2
[Link]() searches only from the beginning of the string and
return match object if found. While [Link]() searches for the
whole string even if the string contains multi-lines and tries to
find a match of the substring in all the lines of string.
11. Discuss how regular expressions can simplify form field 2 CO2 K2
validation in web apps.
Regular expressions help simplify form field validation by
allowing developers to define patterns for acceptable input
formats, such as emails, phone numbers, or usernames, using
concise expressions. Instead of writing multiple if-else
conditions, a single regex can validate the input more efficiently
and clearly. For example, r'^\d{10}$' checks for a 10-digit phone
number. This makes validation faster, reduces code complexity,
and improves maintainability.
12. Illustrate the usage of decorators with a code snippet. 2 CO2 K2

● Decorators allows programmers to modify the behaviour


of a function or class.
A decorator is a function that takes another function as an
argument, extends or modifies its behavior, and returns a new
function. They are commonly used for logging, enforcing access
control,instrumentation, caching, and more
13. Write about the functions that are offered by re 2 CO2 K2
module (RegEx)
Findall-Returns a list containing all matches

17
Search-Returns a Match object if there is a match anywhere in
the string
Split-Returns a list where the string has been split at each match
Sub-Replaces one or many matches with a string s that are
offered by re module(RegEx)
14. Explain how [Link] affects pattern matching in 2 CO2 K2
regex, and write a regex to extract words like "log" or
"error" from a log file, regardless of case.
The [Link] modifier makes regex pattern matching
case-insensitive, so it can match both uppercase and lowercase
variations of a word. For example, "error", "ERROR", and
"Error" will all match.
To find words like "log" or "error" in a log file, ignoring case, the
following regex can be used:
[Link](r'(log|error)', text, [Link])

15. Demonstrate how a Python decorator can be used to print 2 CO2 K2


"Function called" before executing any function.
def log_call(func):
def wrapper(*args, **kwargs):
print("Function called")
return func(*args, **kwargs)
return wrapper

@log_call
def greet():
print("Hello!")
greet()

S. Course
Five Marks Questions Marks Level
No Outcome
1. Explain how the os and sys modules work together in a Python 5 CO2 K2
program that takes file paths as command-line arguments and performs
file-related operations such as checking existence, creating folders,
and deleting files.
The os and sys modules in Python work together to handle file-related
operations efficiently, especially when dealing with command-line
arguments.

sys Module:
The [Link] list captures command-line arguments passed to the
script.

18
It allows the program to accept file paths or folder names dynamically,
instead of hardcoding them.

Example:
import sys
file_path = [Link][1] # Takes the first argument as file path
os Module:

Used for interacting with the file system.

Key functions:

● [Link](path): Checks if a file or folder exists.


● [Link](path): Creates a new folder.
● [Link](path): Deletes a file.
● [Link](path): Checks if the path is a directory.

Example Program:
import os
import sys

path = [Link][1] # Accept file/folder path from command line

if [Link](path):
if [Link](path):
[Link](path)
print("File deleted.")
elif [Link](path):
print("It's a directory.")
else:
[Link](path)
print("Folder created.")
2. Write a Python program to read student records from a CSV file, 5 CO2 K3
calculate the average marks, and write the result to a new tab-separated
file.
import csv

# Read student records from CSV


with open('[Link]', 'r') as infile:
reader = [Link](infile)
header = next(reader) # Skip header row
results = []

for row in reader:


name = row[0]
marks = list(map(float, row[1:])) # Convert marks to float
average = sum(marks) / len(marks)
[Link]([name, average])

# Write name and average to a tab-separated file


with open('[Link]', 'w', newline='') as outfile:
19
writer = [Link](outfile, delimiter='\t')
[Link](['Name', 'Average Marks'])
[Link](results)

print("Average marks written to '[Link]'")


3. A program reads a file containing 10,000 lines of text and processes 5 CO2 K3
each line. Analyze how using buffered file reading (line by line) is
better than loading the whole file into memory. Provide code-based
justification.

When dealing with large files (e.g., 10,000+ lines), buffered file
reading (line-by-line) is more efficient than loading the entire file into
memory at once. This is because it reduces memory usage and
improves scalability.

1. Problem with Loading Entire File


with open('large_file.txt', 'r') as file:
data = [Link]() # Loads all 10,000+ lines into memory
for line in data:
process(line)

Drawback:
● Uses more memory (data stores all lines at once).
● Inefficient for very large files.
● May cause MemoryError on low-RAM systems.

2. Buffered Line-by-Line Reading


with open('large_file.txt', 'r') as file:
for line in file: # Reads one line at a time (buffered)
process(line)

Advantages:
● Only one line is loaded into memory at any time.
● Faster and more memory-efficient for large files.
● Suitable for stream processing and real-time systems.

3. Memory Usage Comparison


Memory
Approach Speed Scalability
Usage
readlines()
High (entire Poor on large
Medium
file) files
for line in file
Low (line by
High Excellent
line)
4. Explain string slicing and indexing with at least three examples that 5 CO2 K2
include both positive and negative indices. Discuss the output in each
case.
String slicing and indexing allow accessing and extracting parts of a
string in Python using positions (indices).

20
● Indexing retrieves a single character using its position.
● Slicing retrieves a range (substring) using the syntax:
● string[start:end] (end is excluded).
● Negative indices count from the end (e.g., -1 = last character).
Example 1: Positive Indexing
s = "Programming"
print(s[0]) # Output: 'P'
print(s[3:8]) # Output: 'gramm'

Example 2: Negative Indexing


s = "Programming"
print(s[-1]) # Output: 'g'
print(s[-4:-1]) # Output: 'min'

● s[-1] returns the last character 'g'.


● s[-4:-1] slices from the 4th-last to 2nd-last character: 'm', 'i', 'n'.

Example 3: Mixed Indexing


s = "Programming"
print(s[1:-1:2]) # Output: 'rgaig'

● s[1:-1:2] starts at index 1, ends before the last, and takes every
2nd character.
Characters taken: 'r', 'g', 'a', 'i', 'g'.
5. Write a Python program that extracts all vowels from a given 5 CO2 K3
paragraph and stores them in a new string. Include upper-case and
lower-case handling. Note: the paragraph refers to any multi-line or
long text input from the user.
# Define vowels
vowels = "aeiouAEIOU"

# Get multi-line paragraph input from user


print("Enter a paragraph (press Enter twice to end):")
lines = []
while True:
line = input()
if line == "":
break
[Link](line)

paragraph = "\n".join(lines)

# Extract vowels
vowel_string = ""
for char in paragraph:
if char in vowels:
vowel_string += char

21
# Display the result
print("\nVowels extracted from the paragraph:")
print(vowel_string)

Explanation:
Accepts multiple lines of input until the user presses Enter twice.
Checks each character in the paragraph.
Appends the character to vowel_string if it is a vowel.
Handles both uppercase and lowercase vowels.

Sample Input:
Enter a paragraph (press Enter twice to end):
Python is Powerful.
It is used worldwide.

Output:
Vowels extracted from the paragraph:
oiooueaioue
6. Krishna Sai is working on a data processing project where each 5 CO2 K3
function performs string transformations like converting text to
uppercase, trimming whitespace, or replacing characters.
His teacher asks him not to modify any existing transformation
logic, but to ensure that each function only receives valid string
inputs.
i) Explain how Krishna Sai can use Python decorators to add input
validation without modifying the original transformation functions.
ii) Demonstrate how to create a decorator @validate_input that
checks whether the input is a string. If the input is not a string, it
should raise a TypeError.
iii) Apply the decorator to the functions to_uppercase,
trim_whitespace, and replace_char, and show sample outputs using
both valid and invalid inputs.
Answer:
Krishna Sai can use a Python decorator to wrap existing
transformation functions. A decorator is a higher-order function that
takes another function as an argument and extends or alters its
behavior without changing the original function code. By placing the
input validation logic in a decorator, Sai ensures input checking is
centralized and reusable, and it does not interfere with the core
transformation logic.
def validate_input(func):
def wrapper(*args, **kwargs):
# Check if all positional and keyword arguments are strings
if not all(isinstance(arg, str) for arg in args) or \
not all(isinstance(val, str) for val in [Link]()):
raise TypeError("All inputs must be strings")
return func(*args, **kwargs)
return wrapper

22
@validate_input
def to_uppercase(text):
return [Link]()

@validate_input
def trim_whitespace(text):
return [Link]()

@validate_input
def replace_char(text, old_char, new_char):
return [Link](old_char, new_char)

# Valid Inputs
print(to_uppercase("hello")) # Output: "HELLO"
print(trim_whitespace(" hello ")) # Output: "hello"
print(replace_char("apple", "p", "b")) # Output: "abble"

7. Kittu is building a Python program to validate user registration details. 5 CO2 K2


The program must validate the following fields without using try-
except or exception handling:
● Username: Alphanumeric and between 5–10 characters
● Password: At least 8 characters, must include letters, numbers,
and special characters
● Email: Must contain an "@" symbol and a valid domain
● Age: Must be a positive integer
● Phone number: Must be exactly 10 digits
● Address: Must not be empty
Explain how conditional checks and regular expressions can be used
to validate inputs without raising exceptions.
Then, demonstrate a Python function register_user() that performs
each check and prints a corresponding error message if any input is
invalid.
Answer:
Python allows input validation using simple conditional statements
(if, else, etc.) without using exceptions. By checking the structure and
content of inputs with if conditions and regex patterns, the program
can:
● Inform users about invalid inputs.
● Continue running smoothly without crashing.
● Print clear guidance messages when an input fails validation.
This approach helps build robust programs in situations where
exceptions are not preferred or supported
import re
def register_user():
username = input("Enter username: ")
if not [Link]() or not (5 <= len(username) <= 10):
print(" Username must be 5-10 alphanumeric characters.")
return
password = input("Enter password: ")
23
if (len(password) < 8 or
not [Link](r"[A-Za-z]", password) or
not [Link](r"[0-9]", password) or
not [Link](r"[^A-Za-z0-9]", password)):
print(" Password must be at least 8 characters long and include letters,
numbers, and special characters.")
return

email = input("Enter email: ")


if not [Link](r"[^@]+@[^@]+\.[^@]+", email):
print(" Invalid email format.")
return

age = input("Enter age: ")


if not [Link]() or int(age) <= 0:
print(" Age must be a positive integer.")
return

phone = input("Enter phone number: ")


if not [Link]() or len(phone) != 10:
print(" Phone number must be a 10-digit number.")
return

address = input("Enter address: ")


if not [Link]():
print(" Address cannot be empty.")
return

print("\n All inputs are valid. Registration successful!")

# Run the validation


register_user()
8. Ritika is developing a Python-based log monitoring tool for her 5 CO2 K2
company. Each log file contains multiple lines, some in lowercase,
some in uppercase, and some mixed. The logs include keywords like
ERROR, warning, Info, and user activity logs like User: admin, user:
guest, etc.
Ritika is asked to:
1. Extract all lines that mention the word “error”, regardless of
how it's capitalized (e.g., ERROR, error, Error, etc.).
2. Find and extract all usernames that follow the format User:
<username> or user: <username>, using capturing groups.
3. Print all lines that contain the word "login" or "access", in any
case (e.g., Login, ACCESS, accessDenied).
She must use regex modifiers and efficient patterns in Python using
the re module — without writing multiple if statements or converting
text manually to lowercase.
Explain how Ritika can use regex modifiers like [Link],
[Link], and patterns to complete her task efficiently.
Then, write a Python function process_logs(log_string) that performs
all three operations on a given multiline log string and prints the
results.
Answer:

24
Python’s re module, which supports modifiers (also called flags) that
change the behavior of pattern matching:
1. [Link] (re.I)
● Makes the pattern case-insensitive, so it can match "error",
"ERROR", or "eRrOr" without converting the input manually.
2. [Link] (re.M)
● Treats each line in a multiline string as a separate string.
● This allows anchors like ^ (start of line) and $ (end of line) to
match correctly on each line, not just the start and end of the
whole string.
3. Regex Patterns
● To match “error” in any case: r".*error.*" with
[Link]
● To extract usernames: r"User:\s*(\w+)" with
[Link] to match both User: and user:
● To match lines with “login” or “access”: r".*(login|access).*"
with [Link]
import re

def process_logs(log_string):
# 1. Extract all lines containing "error" (case-insensitive)
error_lines = [Link](r"^.*error.*", log_string, [Link] |
[Link])
print(" Lines with 'error':")
for line in error_lines:
print(line)

# 2. Extract all usernames using capturing group


usernames = [Link](r"User:\s*(\w+)", log_string,
[Link])
print("\n Usernames found:")
for user in usernames:
print(user)

# 3. Print lines with "login" or "access" (case-insensitive)


login_access_lines = [Link](r"^.*(login|access).*", log_string,
[Link] | [Link])
print("\n Lines with 'login' or 'access':")
for line in login_access_lines:
print(line)
9. Sameer is working on a competitive programming task that requires 5 CO2 K3
frequent conversion between number systems (binary, decimal, octal,
and hexadecimal). He receives a list of numbers in different formats
and needs to:
1. Identify the base of each number using prefixes (0b, 0o, 0x)
or assume decimal if no prefix is found.
2. Convert all the numbers to decimal and store them in a list.
3. From that list, find:
o The maximum and minimum values
o The average (mean) of all numbers (rounded to 2
decimal places)

25
Extend the program to calculate the maximum, minimum, and
average of the decimal list. Round the average to 2 decimal
places.

Answer:
In Python, numbers from different bases can be identified using their
prefixes:
● 0b → binary (base 2)
● 0o → octal (base 8)
● 0x → hexadecimal (base 16)
●No prefix → decimal (base 10)
Python’s int(string, base) function can convert any valid base-
prefixed string to decimal.
For example:
● int("0b1010", 2) → 10
● int("0xF", 16) → 15

def analyze_numbers(num_list):
decimal_numbers = []

for num in num_list:


if [Link]("0b"):
decimal_numbers.append(int(num, 2))
[Link]("0o"):
decimal_numbers.append(int(num, 8))
[Link]("0x"):
decimal_numbers.append(int(num, 16))
else:
decimal_numbers.append(int(num)) # Assume decimal

maximum = max(decimal_numbers)
minimum = min(decimal_numbers)
average = round(sum(decimal_numbers) / len(decimal_numbers),
2)

return {
"Decimal Numbers": decimal_numbers,
"Max": maximum,
"Min": minimum,
"Average": average
● }
10. A college requires students to enter their registration number in a 5 CO2 K3
fixed format during form submission. The expected format is:
● First 2 characters: uppercase letters (college code)
● Next 2 digits: last two digits of the admission year (e.g., 24
for 2024)
● Next 3 characters: branch code in uppercase letters (e.g., CSE,
ECE)
● Last 3 digits: unique student number (e.g., 001 to 999)

26
Example of a valid registration number: CS24CSE123
As a backend developer, Ravi must ensure the system validates the
input using Python regular expressions without using if conditions or
string slicing.
Apply a Python regular expression with [Link]() to
check whether the entered registration number follows the fixed
format.
Answer:

To validate the registration number format, Ravi can use the


following regex pattern:
regex
CopyEdit
^[A-Z]{2}[0-9]{2}[A-Z]{3}[0-9]{3}$

import re

def is_valid_regno(reg_no):
pattern = r'^[A-Z]{2}[0-9]{2}[A-Z]{3}[0-9]{3}$'
return [Link](pattern, reg_no) is not None
print(is_valid_regno("CS24CSE123"))
print(is_valid_regno("cs24cse123"))
print(is_valid_regno("CSE2023"))

Unit – III
Unit 3 Exception Handling and Multi-Threading in Python L-3Hours
Unit Contents:
Exception handling: try, except and finally block, handling multiple exceptions, raise an exception,
User defined exception- python multithreading- thread and threading module- Synchronizing
Threads in Python.
Case Study: Development of student performance evaluation report.

S. Two Marks Questions.


Course
No Marks Level
Outcome

1. Find and correct the error in the following Python code:

try:
number = int("abc")
print("Converted number:", number) 2 CO3
except: K1
print("Some error occurred")
finally:
print("Completed")

27
Output:
try:
number = int("abc")
print("Converted number:", number)
except ValueError:
print("Some error occurred")
finally:
print("Completed")
2. Explain the difference between syntax errors and exceptions. 2 K2

Syntax Errors: Errors in code structure, caught at compile-time (e.g.,


missing colon).
CO3
Exceptions: Errors during execution (e.g., division by zero, type
errors).

3. Select two integers as input and performs division. 2 K1

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
CO3
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
4. Identify a program that accepts a list of numbers and a position from 2 K1
the user. Print the number at that position.
try:
nums = list(map(int, input("Enter numbers separated by space:
").split()))
CO3
pos = int(input("Enter position: "))
print("Element at position:", nums[pos])
except IndexError:
print("Invalid index")

28
except ValueError:
print("Invalid input")
5. What is the output? 2 K1

def f():
try:
return 1
finally: CO3
return 2
print(f())
Output:2

6. Compute a code. 2 K2

class MyError(Exception):
pass
def g():
raise MyError("Oops")
try:
CO3
g()
except Exception as e:
print("Handled:", type(e).__name__)
What gets printed?
Output: Handled: MyError

7. Predict the output. 2 K2

try:
x = int("10")
except ValueError:
print("Not an integer") CO3
else:
print("It is an integer")
finally:
print("Exiting")

29
Output:
It is an integer
Exiting
8. How would you modify the following code to only catch 2 K1
ZeroDivisionError, but let other exceptions propagate?
try:
# some code that might fail
except Exception:
print("Error")
Output: CO3

try:
except ZeroDivisionError:
print("Division by zero error")
9. Define Thread with an example. 2 K1

A thread is a lightweight subprocess used to run code concurrently.


import threading
def hello():
CO3
print("Hello from thread")
thread = [Link](target=hello)
[Link]()
[Link]()
10. What is the output of the following? 2 K1

import threading
def print_hello():
for i in range(3):
print("Hello", i)

t1 = [Link](target=print_hello)
CO3
[Link]()
print("Done")
Output:
Hello 0
Hello 1
Hello 2
Done

30
11. Find the output for the program. 2 K1

import threading
x=0
def increment():
global x
for _ in range(100000):
x += 1
t1 = [Link](target=increment)
CO3
t2 = [Link](target=increment)
[Link]()
[Link]()
[Link]()
[Link]()
print(x)
Output: Unpredictable (less than 200000), due to race conditions.

12. Differentiate between join() and start() methods in Python threading. 2 K2

● start(): Begins thread execution.


CO3
● join(): Waits for thread to finish before continuing.

13. Explain the purpose of using [Link]() in multithreading? 2 K2

To prevent race conditions by allowing only one thread to access


critical sections at a time. CO3

14. Illustrate the use of the [Link]() class in Python? 2 K2

To create and manage threads using a target function. CO3

15. Discuss the Output for the code given below. 2 K2

import threading
x=0 CO3
lock = [Link]()
def update():

31
global x
[Link]()
x += 1
[Link]()
threads = []
for i in range(5):
t = [Link](target=update)
[Link](t)
[Link]()
for t in threads:
[Link]()
print(x)
Output: 5 (due to proper locking mechanism)

Five Marks Questions. Course


Marks Level
Outcome
1. Execute a function calculate_grade(mark) that: 5 CO3 K3

Raises TypeError if mark is not a number.


Raises ValueError if mark is outside 0–100.
Returns 'A', 'B', 'C', 'D', or 'F' based on mark thresholds.
Wrap this in input-handling code using try, except, and finally.
def calculate_grade(mark):
# Check if input is a number
if not isinstance(mark, (int, float)):
raise TypeError("Mark must be a number.")

# Check if mark is in valid range


if not (0 <= mark <= 100):
raise ValueError("Mark must be between 0 and 100.")

32
# Grade boundaries
if mark >= 90:
return 'A'
elif mark >= 80:
return 'B'
elif mark >= 70:
return 'C'
elif mark >= 60:
return 'D'
else:
return 'F'

# Wrapping input handling


try:
user_input = input("Enter the mark: ")
mark = float(user_input)
grade = calculate_grade(mark)
print("Grade:", grade)
except TypeError as te:
print("TypeError:", te)
except ValueError as ve:
print("ValueError:", ve)
finally:
print("Grade calculation complete.")
2. Illustrate Python program using raise to manually trigger a ValueError if a 5 CO3 K2
user enters an empty string as input. Explain the role of the raise keyword.
● Explain what raise does.-2 m

● Provide a working code snippet using raise ValueError when the


string is empty.-1m

Include try-except-finally blocks to handle the error and ensure the program
completes.-2m
3. Explain with example how to raise and handle user-defined exceptions in 5 CO3 K2
Python.

● Define what a user-defined exception is.1m

33
● Show how to create a custom exception class by inheriting from
Exception.1m
● Write a program to raise the exception when a specific condition is
met (e.g., negative age input).2m

Use try-except to catch and handle the exception gracefully.1m

4. A teacher wants to enter student marks to calculate grades. However, if the 5 CO3 K3
input is not a number or is outside 0–100, it should raise an error. Apply the
concepts of exception in python to solve the scenario.

TypeError if input is not a number.1m


ValueError if the mark is not in the range 0–100.1m

try-except-finally for complete error handling.1m


5. Build a calculator app, two numbers are input by the user. The program 5 CO3 K3
should perform division.

● Handle ValueError if the input is not a number. 1m


● Handle ZeroDivisionError if the denominator is 0.1m
● Print "Division result: <result>" or appropriate error messages.1m

Use try-except-else-finally.2m

6. Explain multithreading in Python with an example. How does it improve 5 CO3 K2


program performance?
● Define multithreading and its purpose.1m

● Discuss how Python uses the threading module.1m

● Write a simple example to demonstrate multithreading.1m

● Mention use cases such as I/O-bound tasks.1m

Explain the role of start() and join() in managing threads.1m


7. Execute a Python program that creates three threads to print “Hello from 5 CO3 K3
Thread-1”, “Hello from Thread-2”.
Output:
import threading
# Define the function each thread will run
def greet(thread_name):
print(f"Hello from {thread_name}")

# Create three threads


t1 = [Link](target=greet, args=("Thread-1",))

34
t2 = [Link](target=greet, args=("Thread-2",))
t3 = [Link](target=greet, args=("Thread-3",))

# Start the threads


[Link]()
[Link]()
[Link]()

# Wait for all threads to finish


[Link]()
[Link]()
[Link]()
8. Develop a program that creates three threads. Each thread should 5 CO3 K3
print a greeting message in the format:
Hello from <Thread-Name>
Use the threading module and define a function that each thread
executes.
Constraints:

● Use only the threading module from Python standard


library.

● The thread names must be: Thread-1, Thread-2, Thread-3.


Sample Input: (no input required)
Sample Output: (Order may vary)
csharp
CopyEdit
Hello from Thread-1
Hello from Thread-2
Hello from Thread-3
Output:
import threading

# Function each thread will execute


def greet(thread_name):
print(f"Hello from {thread_name}")

# Create threads with names Thread-1, Thread-2, Thread-3


t1 = [Link](target=greet, args=("Thread-1",))
t2 = [Link](target=greet, args=("Thread-2",))
t3 = [Link](target=greet, args=("Thread-3",))

# Start the threads

35
[Link]()
[Link]()
[Link]()

# Wait for threads to finish


[Link]()
[Link]()
[Link]()
9. Implement the multithreaded program that calculates the sum of a 5 CO3 K3
list of integers. Split the list into two halves and assign each half to a
separate thread. Return the total sum after both threads complete.
Constraints:

● Use 2 threads only.

● The list will contain up to 100 integers.

● All numbers are between 1 and 1000.


Sample Input:
10 20 30 40 50 60
Sample Output:
Total Sum: 210
Output:
import threading

# Global variable to hold partial sums


partial_sums = [0, 0]

# Function to compute sum of a slice


def compute_sum(numbers, index):
partial_sums[index] = sum(numbers)

# Input
input_str = input("Enter numbers separated by space:\n")
numbers = list(map(int, input_str.strip().split()))

# Split list into two halves

mid = len(numbers) // 2
first_half = numbers[:mid]
second_half = numbers[mid:]

# Create two threads


t1 = [Link](target=compute_sum, args=(first_half, 0))

36
t2 = [Link](target=compute_sum, args=(second_half, 1))

# Start threads
[Link]()
[Link]()

# Wait for both threads to complete


[Link]()
[Link]()

# Compute total sum


total = partial_sums[0] + partial_sums[1]
print("Total Sum:", total)
10. Problem Statement 5 CO3 K3
Five philosophers sit around a circular table. Each philosopher does only two
things:Thinks and Eats
However, to eat, a philosopher needs two chopsticks — one from their left
and one from their right. Chopsticks are placed between each pair of adjacent
philosophers.
Implement a program that ensures:
No philosopher will starve (i.e., everyone eventually gets to eat).
No deadlocks occur (e.g., no situation where all philosophers are waiting
forever for chopsticks).
Proper synchronization using mutex locks or semaphores.
You must simulate the scenario using Python’s threading module and print
the behavior of each philosopher as they think and eat.
Input Format
There is no standard input. You must simulate 5 philosophers using threads.
Output Format
Each philosopher should output their activity in the following format:
import threading
import time
import random
# Number of philosophers
NUM_PHILOSOPHERS = 5

# Each chopstick is a Lock


chopsticks = [[Link]() for _ in range(NUM_PHILOSOPHERS)]

# Limit the number of philosophers that can try to eat at the same time to
prevent deadlock

37
# At most 4 philosophers can try to pick up chopsticks at a time
waiter = [Link](NUM_PHILOSOPHERS - 1)

def philosopher(phil_id):
for i in range(3): # Let each philosopher eat 3 times
print(f"Philosopher {phil_id} is thinking")
[Link]([Link](0.5, 1.5)) # Thinking

print(f"Philosopher {phil_id} is hungry")

[Link]() # Ask permission to try picking up chopsticks

left = phil_id
right = (phil_id + 1) % NUM_PHILOSOPHERS

# Acquire left and right chopsticks


chopsticks[left].acquire()
print(f"Philosopher {phil_id} picked up left chopstick")

chopsticks[right].acquire()
print(f"Philosopher {phil_id} picked up right chopstick")

# Eating
print(f"Philosopher {phil_id} is eating")
[Link]([Link](0.5, 1.5))

# Put down right and left chopsticks


chopsticks[right].release()
print(f"Philosopher {phil_id} put down right chopstick")

chopsticks[left].release()
print(f"Philosopher {phil_id} put down left chopstick")

[Link]() # Notify that one philosopher is done

# Create and start philosopher threads


threads = []
for i in range(NUM_PHILOSOPHERS):
t = [Link](target=philosopher, args=(i,))

38
[Link](t)
[Link]()

# Wait for all threads to complete


for t in threads:
[Link]()

print("Dining completed.")
Unit – IV
Unit 4 Data Analysis using Python libraries L- 3 Hours
Unit Contents:
NumPy: Introduction, NdArray object, Data Types, Array Attributes, Indexing and
Slicing, Array manipulation, mathematical functions, Matplotlib; Pandas: Introduction to
pandas data structures-series-Data Frame-Panel-basic functions-descriptive statistics
function-iterating data frames-statistical functions-aggregations-visualization- plotting
graphs using plotly Library.
Case Study: Sales Forecasting

[Link] Two Marks Questions. Course


Marks Level
Outcome
1. Find and correct the error in the following Python code: 2 CO4 K1

try:
number = int("abc")
print("Converted number:", number)
except:
print("Some error occurred")
finally:
print("Completed")

Output:
try:
number = int("abc")
print("Converted number:", number)
except ValueError:
print("Some error occurred")
finally:
print("Completed")
2. Explain the difference between syntax errors and exceptions. 2 CO4 K2

Syntax Errors: Errors in code structure, caught at compile-time (e.g.,


missing colon).

39
Exceptions: Errors during execution (e.g., division by zero, type
errors).
3. Select two integers as input and performs division. 2 CO4 K1

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:

print("Invalid input")

4. Identify a program that accepts a list of numbers and a position from 2 CO4 K1
the user. Print the number at that position.
try:
nums = list(map(int, input("Enter numbers separated by space:
").split()))
pos = int(input("Enter position: "))
print("Element at position:", nums[pos])
except IndexError:
print("Invalid index")
except ValueError:
print("Invalid input")
5. What is the output? 2 CO4 K1

def f():
try:
return 1
finally:
return 2
print(f())
Output:2

6. Compute a code. 2 CO4 K2

40
class MyError(Exception):
pass
def g():
raise MyError("Oops")
try:
g()
except Exception as e:
print("Handled:", type(e).__name__)
What gets printed?
Output: Handled: MyError

7. Predict the output. 2 CO4 K2

try:
x = int("10")
except ValueError:
print("Not an integer")
else:
print("It is an integer")
finally:
print("Exiting")
Output:
It is an integer
Exiting
8. How would you modify the following code to only catch 2 CO4 K1
ZeroDivisionError, but let other exceptions propagate?
try:
# some code that might fail
except Exception:
print("Error")
Output:
try:
except ZeroDivisionError:
print("Division by zero error")
9. Define Thread with an example. 2 CO4 K1

A thread is a lightweight subprocess used to run code concurrently.

41
import threading
def hello():
print("Hello from thread")
thread = [Link](target=hello)
[Link]()
[Link]()
10. What is the output of the following? 2 CO4 K1

import threading
def print_hello():
for i in range(3):
print("Hello", i)

t1 = [Link](target=print_hello)
[Link]()
print("Done")
Output:
Hello 0
Hello 1
Hello 2
Done
11. Find the output for the program. 2 CO4 K1

import threading
x=0
def increment():
global x
for _ in range(100000):
x += 1
t1 = [Link](target=increment)
t2 = [Link](target=increment)
[Link]()
[Link]()
[Link]()

42
[Link]()
print(x)
Output: Unpredictable (less than 200000), due to race conditions.

12. Differentiate join() and start() methods in Python threading. 2 CO4 K2

● start(): Begins thread execution.

● join(): Waits for thread to finish before continuing.

13. Explain the purpose of using [Link]() in multithreading? 2 CO4 K2

To prevent race conditions by allowing only one thread to access


critical sections at a time.

14. Illustrate the use of the [Link]() class in Python? 2 CO4 K2

To create and manage threads using a target function.

15. Discuss the Output for the code given below. K2

import threading
x=0
lock = [Link]()
def update():
global x
[Link]()
x += 1
[Link]()
threads = []
for i in range(5):
t = [Link](target=update)
[Link](t)
[Link]()
for t in threads:
[Link]()
print(x)
Output: 5 (due to proper locking mechanism)

43
Five Marks Questions. Course
Marks Level
Outcome
1. Explain what a NumPy ndarray object is and how it differs from a 5 CO4 K2
Python list, highlighting its advantages for numerical computation.
Discuss at least three key attributes of the ndarray object
(e.g., ndim, shape, size, dtype) and provide a brief example for each.

A NumPy ndarray (n-dimensional array) is the core data


structure provided by the NumPy library. It represents a multi-
dimensional, homogeneous array of fixed-size items (i.e., all
elements have the same data type), optimized for high-
performance numerical computations.

Key Attributes of ndarray

1. ndim – Number of Dimensions

Indicates how many dimensions the array has.

import numpy as np

arr = [Link]([[1, 2], [3, 4]])

print([Link]) # Output: 2

2. shape – Tuple of Array Dimensions

Returns a tuple indicating the size in each dimension (rows,


columns, etc.)

print([Link]) # Output: (2, 2)

3. size – Total Number of Elements

Gives the total number of elements in the array.

print([Link]) # Output: 4

4. dtype – Data Type of Elements

Shows the data type of elements stored in the array.

print([Link]) # Output: int64 (or int32 depending on system)

44
2. 5 CO4 K2
Explain the features of NumPy and its importance in scientific
computing.

Answer:
NumPy (Numerical Python) is a powerful Python library used for
numerical and scientific computing. Its key features include:

● N-dimensional arrays (ndarray): Efficient data storage


for large data sets.

● Vectorized operations: Faster operations without explicit


loops.

● Broadcasting: Allows operations between arrays of


different shapes.

● Mathematical functions: Includes statistical,


trigonometric, and algebraic functions.

● Integration with C/C++: Enables performance


optimization.
It is widely used in data analysis, machine learning, and
simulations due to its speed and flexibility.

3. 5 CO4 K2
Classify the various methods of indexing and slicing NumPy
arrays to access specific elements or subsets of data. Provide code
examples to demonstrate integer indexing, boolean indexing, and
array slicing.

NumPy provides several powerful methods to access or modify


specific elements or subsets of an array:

1. Integer Indexing

Integer indexing allows you to access specific elements using their


row and column positions.

� Example:

import numpy as np

array = [Link]([[10, 20, 30, 40],

[50, 60, 70, 80],

45
[90, 100, 110, 120]])

row_indices = [Link]([0, 1, 2])

col_indices = [Link]([1, 2, 3])

selected_elements = array[row_indices, col_indices]

print(selected_elements) # Output: [20 70 120]

� This selects elements (0,1), (1,2), and (2,3).

2. Boolean Indexing

Boolean indexing is used to filter elements based on conditions. It


returns a new array consisting only of the elements that meet the
condition.

� Example:

array = [Link]([10, 25, 35, 45, 5, 60])

condition = array > 30

filtered_elements = array[condition]

print(filtered_elements) # Output: [35 45 60]

� Here, only the elements greater than 30 are selected.

filtered_elements = array[array > 30]

Array Slicing

Array slicing is similar to list slicing in Python. It allows you to


select a range of elements from the array.

� Example:

array = [Link]([[1, 2, 3, 4],

[5, 6, 7, 8],

[9, 10, 11, 12]])

46
# Slicing rows 0 and 1, and columns 1 and 2

subset = array[0:2, 1:3]

print(subset)

# Output:

# [[2 3]

# [6 7]]

� array[start_row:end_row, start_col:end_col] gives a subarray.

4. 5 CO4 K2
Discuss the role of NumPy's mathematical functions in data
analysis. Explain how you can leverage NumPy arrays to perform
calculations for a rolling mean. Then, demonstrate how to visualize
this rolling mean using Matplotlib, including setting plot size and
adding a [Link] Mathematical Functions in Data Analysis

NumPy provides efficient, vectorized mathematical functions that


are essential in data analysis for:

● Performing aggregations (e.g., sum(), mean(), std())


● Applying element-wise operations (e.g., [Link](), [Link](),
[Link]())
● Conducting statistical analysis
● Enabling rolling and window-based operations with tools
like sliding_window_view

These functions operate directly on arrays, making calculations


fast and memory-efficient compared to Python loops.

Rolling Mean Using NumPy

A rolling mean (also called moving average) smooths out short-


term fluctuations in data by averaging elements over a sliding
window.

We can use [Link].stride_tricks.sliding_window_view() to


generate overlapping windows.

Visualizing the Rolling Mean with Matplotlib

47
We can visualize both the original data and the rolling mean using
[Link].

● NumPy's mathematical functions are crucial for fast and


clean numerical analysis.
● The sliding_window_view() function helps compute
rolling statistics like moving averages efficiently.

Matplotlib allows you to visually interpret these calculations


with easy customization options like legends, sizing, and
gridlines.
5. 5 CO4 K2
Consider a DataFrame df with columns 'Name', 'Age', 'City', and
'Marks'. Explain how to:

● Retrieve the first five rows.

● Calculate descriptive statistics (mean, median, standard


deviation) for the 'Marks' column. You can mention
methods like mean(), median(), and std() or simply
describe the output of [Link]().

● Filter the DataFrame to include only rows where 'Age' is


greater than 30.

● Iterate over the rows of the DataFrame, describing why


this approach is generally discouraged for performance,
and recommend alternatives for large datasets.

1. Retrieve the First Five Rows

To view the first five rows of the DataFrame:

[Link]()

[Link]() by default returns the top 5 rows, useful for previewing


data.

2. Calculate Descriptive Statistics for 'Marks'

Method 1: Use individual functions

mean_marks = df['Marks'].mean()

48
median_marks = df['Marks'].median()

std_marks = df['Marks'].std()

print("Mean:", mean_marks)

print("Median:", median_marks)

print("Standard Deviation:", std_marks)

Method 2: Use describe() to get summary statistics

df['Marks'].describe()

This returns count, mean, std, min, 25%, 50% (median), 75%, and
max values.

3. Filter Rows Where 'Age' is Greater Than 30

Use a boolean condition to filter:

filtered_df = df[df['Age'] > 30]

This creates a new DataFrame with only rows where 'Age' > 30.

4. Iterate Over Rows of the DataFrame

Method:

for index, row in [Link]():

print(f"Name: {row['Name']}, Age: {row['Age']}, City:


{row['City']}, Marks: {row['Marks']}")

6. Apply each type of data skew impacts data visualizations and 5 CO4 K3
suggest a suitable type of chart or plot to effectively represent
skewed data.

Data skewing refers to a situation in which the distribution of data


is not symmetrical—it is "skewed" or "lopsided" either to the left
or to the right.

� Types of Data Skew


1. Right Skew (Positive Skew)
Long tail to the right (higher values).

49
Most data points are clustered at the lower end of the scale.

A few high values (outliers) drag the tail to the right.

Example:
Income distribution: Most people earn between ₹20k–₹80k/month,
but a few earn ₹5L–₹10L/month.
Numerical Indicators:
Mean > Median > Mode

The mean is misleading because it's pulled up by the high earners.

� Impact on Visualization:
Bar graphs or histograms will have a sharp peak on the left and a
long tail on the right.

Line plots may show a sudden spike, hiding the bulk of the data.

2. Left Skew (Negative Skew)


Long tail to the left (lower values).

Most data points are at the higher end of the scale.

A few low outliers drag the tail to the left.

Example:
Exam scores where most students scored 80–100, but a few scored
10–30.
Numerical Indicators:
Mean < Median < Mode

The mean looks lower than what most students scored, creating a
false impression.

� Impact on Visualization:
Histogram will have a peak on the right with a tail on the left.

Averages may understate actual performance.

Why Skew Matters in Data Analysis & Visualization


Misleading averages:

In skewed data, the mean is influenced by outliers and may not


represent the "typical" value.

Poor scaling:
50
In charts, skew can cause most values to appear bunched together,
hiding variation.

Wrong assumptions:

Many statistical models assume normal distribution—skew


violates that and can lead to incorrect conclusions.

� Visualizations Suitable for Skewed Data


1. Histogram
Shows the distribution and highlights skew direction.
import numpy as np
import [Link] as plt

# Example: Right-skewed data


data = [Link](scale=50, size=1000)

[Link](figsize=(8, 4))
[Link](data, bins=40, color='lightblue', edgecolor='black')
[Link]("Right-Skewed Data Distribution")
[Link]("Value")
[Link]("Frequency")
[Link](True)
[Link]()
2. Box Plot
Shows median, quartiles, and highlights outliers clearly.
[Link](data, vert=False)
[Link]("Box Plot of Right-Skewed Data")
[Link]("Value")
[Link](True)
[Link]()
3. Logarithmic Scale Plot
Helps normalize the effect of large values by compressing the
scale.

[Link](data, bins=40, log=True, color='lightgreen',


edgecolor='black')
[Link]("Histogram with Log Scale")
[Link]("Value")

51
[Link]("Log(Frequency)")
[Link](True)
[Link]() ng how we interpret the data.

7. Explain the concept of iterating over DataFrames in Pandas. 5 CO4 K2


Describe the different methods used, their advantages and
limitations, and best practices when handling large datasets.

Iteration over a DataFrame in Pandas refers to the process of


accessing each row or column individually in a loop. This is often
used when applying custom logic, transforming data, or extracting
information. However, iteration is not the most efficient method
in Pandas due to its reliance on Python loops, which are slower
than vectorized operations.

� Methods of Iteration:

1. iterrows()
o Returns each row as a Series with index and
column names.
o Syntax: for index, row in [Link]():
o Advantages:
▪ Easy to understand and use.
▪ Access by column names.
o Limitations:
▪ Slower for large DataFrames.
▪ May cause data type inconsistencies.
▪ Not memory-efficient.
2. itertuples()
o Returns each row as a named tuple.
o Syntax: for row in [Link]():
o Advantages:
▪ Faster than iterrows().
▪ Preserves data types better.
▪ More memory-efficient.
o Limitations:
▪ Tuple values are immutable.
▪ Less readable for beginners.
3. apply() function
o Applies a function to each row or column.
o Syntax: [Link](function, axis=1)
o Advantages:
▪ Vectorized and efficient.
▪ Can apply complex logic.
o Limitations:
▪ Slightly slower than pure vectorized
operations.

52

May not always improve performance if
misused.
4. Vectorized Operations (Best Practice)
o Uses Pandas/Numpy to apply operations across
entire columns.
o Advantages:
▪ Fastest and most efficient.
▪ Recommended for mathematical and logical
operations.
o Limitations:
▪ Less flexible for complex custom logic.

Performance Implications:

● Iteration methods like iterrows() are slow and memory-


heavy, especially for large datasets.
● It is generally better to avoid explicit loops and use
vectorized or functional methods like apply() or direct
operations.
8. Construct an array of all combinations of two NumPy arrays? 5 CO4 K3
Solution:
Syntax:
[Link](*xi, copy=True, sparse=False, indexing='xy')

Program:
import numpy as np

a = [Link]([1, 2])
b = [Link]([4, 6])

print("Array-1")
print(a)

print("\nArray-2")
print(b)

res = [Link]([Link](a, b)).[Link](-1, 2)

print("\nCombine array:")
print(res)

Output:
Array-1
[1 2]

Array-2
[4 6]

Combine array:
[[1 4]
53
[1 6]
[2 4]
[2 6]]

9. Compute the code to Convert an image to NumPy array and saveit 5 CO4 K3
to CSV file using Python?
● Read the image using PIL or OpenCV

● Convert the image to a NumPy array

● (Optional) Flatten or reshape the array

● Save the array to a CSV file using NumPy or Pandas

import cv2
import numpy as np
import pandas as pd

# Step 1: Read image using OpenCV (as NumPy array)


img = [Link]("[Link]") # Reads image as BGR
format

# Step 2: Convert BGR to RGB


img_rgb = [Link](img, cv2.COLOR_BGR2RGB)

# Step 3: Flatten and reshape


flattened_array = img_rgb.reshape(-1, 3)

# Step 4: Save to CSV


df = [Link](flattened_array, columns=['Red',
'Green', 'Blue'])
df.to_csv("image_pixels.csv", index=False)

print("Image saved to image_pixels.csv")

Output:

Image Pixels (visual representation):


[[(255, 0, 0), (0, 255, 0)],
[(0, 0, 255), (255, 255, 0)]]
10. Plot line graph from NumPy array 5 CO4 K2
Different functions used are explained below:
● [Link](start, end): This function returns equally
spaced values from the interval [start, end).
● [Link](): It is used to give a title to the graph. Title is
passed as the parameter to this function.
● [Link](): It sets the label name at X-axis. Name of X-
axis is passed as argument to this function.

54
● [Link](): It sets the label name at Y-axis. Name of Y-
axis is passed as argument to this function.
● [Link](): It plots the values of parameters passed to it
together.
● [Link](): It shows all the graph to the console.
# importing the modules
import numpy as np
import [Link] as plt

# data to be plotted
x = [Link](1, 11)
y=x*x

# plotting
[Link]("Line graph")
[Link]("X axis")
[Link]("Y axis")
[Link](x, y, color ="red")
[Link]()

Output:

Example 2 :
# importing the library
import numpy as np
import [Link] as plt

# data to be plotted
x = [Link](1, 11)
y = [Link]([100, 10, 300, 20, 500, 60, 700, 80, 900, 100])

# plotting
[Link]("Line graph")
[Link]("X axis")
[Link]("Y axis")
[Link](x, y, color ="green")
[Link]()
Output:

55
Unit – V
Unit 5 : UI and Game design using Python libraries L-3 Hours
Unit Contents:
Tkinter module: introduction, widgets, standard attributes, Geometry management, Tkinter Event
Handling; Database connectivity with MySQL. PyGame Module - PyGame Concepts- Basic Game
Design-Sprites-Sprite Groups-Custom Events-Collision Detection-Sprite Images-Game Speed-Sound
Effects.
Case Study: Angry bird game and UI design

Two Marks Questions. Course


Marks Level
Outcome
1. Explain the primary role of the main event loop ([Link]()) 2 CO5 K2
in a Tkinter application.
The main event loop ([Link]()) is an infinite loop that listens
for user events (like mouse clicks, key presses) and system events. It
keeps the window visible and responsive, updating the UI as needed.
2. Identify the method used in PyGame to check for collisions 2 CO5 K1
between two sprites.
A 'Sprite' is a 2D image or animation that represents a single object
in a game (like a character, an enemy, or a bullet) and can be moved
and manipulated independently.
3. Summarize the steps to connect a Python script to a MySQL 2 CO5 K2
database using a library like mysql-connector-python.
[Link] the database connector library. 2. Establish a connection
using connect() with host, user, and password. 3. Create a cursor
object from the connection. 4. Execute SQL queries using
[Link](). 5. Close the connection.
4. Predict the output or behavior of the following Tkinter code. 2 CO5 K2
import tkinter as tk
root = [Link]()
[Link](root, text="Hello").pack(side=[Link])
[Link](root, text="World").pack(side=[Link])
[Link]()
The code will create a small window. A label with the text "Hello"
will be packed against the left edge of the window, and a label with
"World" will be packed against the right edge. They will be
vertically centered.
5. State the purpose of the [Link]() function. 2 CO5 K1
[Link]() initializes all the imported PyGame modules that are
required to make PyGame work, such as the display, font, and sound
modules. It must be called before any other PyGame function.
6. Explain the concept of a "custom event" in PyGame and provide 2 CO5 K2
an example scenario where it would be useful.
A custom event is a user-defined event that can be posted to
PyGame's event queue. It's useful for scheduling actions, like
spawning an enemy every 5 seconds, without cluttering the main
loop with timer logic.
56
7. Compare the coordinate systems of Tkinter and PyGame. Where 2 CO5 K2
is the origin (0,0) located in each?
Tkinter: The origin (0,0) is at the top-left corner of the widget or
window. The Y-axis increases downwards.
PyGame: The origin (0,0) is at the top-left corner of the display
Surface. The Y-axis increases downwards. They use the same
convention.
8. Demonstrate how you would bind the <Return> key (Enter key) 2 CO5 K2
to a function named on_submit in a Tkinter window.
[Link]('<Return>', on_submit) where root is the Tkinter window
instance and on_submit is the handler function.
9. Identify the module and function used to update the entire 2 CO5 K1
PyGame display screen.
The module is [Link], and the function is update() or flip().
So, [Link]().
10. Classify the following Tkinter widgets based on their primary 2 CO5 K2
function (e.g., Input, Display, Container): Frame, Entry, Label,
Button.
Frame: Container
Entry: Input
Label: Display
Button: Input/Action
11. Explain how [Link]() simplifies game 2 CO5 K2
development, especially for handling multiple game objects.
[Link]() acts as a container for multiple sprites. It
simplifies development by allowing you to call update() and draw()
on the entire group at once, rather than iterating through each sprite
individually. It also has built-in methods for collision detection
between a sprite and a group.
12. Interpret the meaning of the blit() method in PyGame. What are 2 CO5 K2
its essential arguments?
The blit() method is used to draw one image (a source Surface) onto
another (a destination Surface). Its essential arguments are the source
surface to draw and a destination coordinate (x, y) or a Rect object
specifying the top-left corner for the draw operation.
destination_surface.blit(source_surface, (x, y)).
13. Contrast a game's frame rate (FPS) with its game speed. How can 2 CO5 K2
you control the frame rate in PyGame?
Frame Rate (FPS): How many times the screen is redrawn per second.
It affects the smoothness of animations.
Game Speed: The rate at which game logic and object positions are
updated. It should be independent of FPS to ensure consistent
gameplay on different computers.
You can control FPS in PyGame using
[Link]().tick(FPS_VALUE).
14. Name the Tkinter widget used to get a single line of text input 2 CO5 K1
from a user.
The Entry widget is used for single-line text input.

57
15. Illustrate the difference between a Surface and a Rect object in 2 CO5 K2
PyGame.
Surface: A blank canvas or image object in PyGame that you can draw
on. The main display screen is a Surface.
Rect: A [Link] object represents a rectangular area, defined by
its top-left corner (x, y) and its width and height. It is used for
positioning and collision detection, not for drawing.

Five Marks Questions. Course


Marks Level
Outcome
1. Develop a simple Tkinter application that functions as a 5 CO5 K3
temperature converter. It must have an Entry widget to input
Celsius, a Button to "Convert", and a Label to display the result in
Fahrenheit.
import tkinter as tk

def convert_temp():
try:
celsius = float(entry_celsius.get())
fahrenheit = (celsius * 9/5) + 32
label_result.config(text=f"Result: {fahrenheit:.2f} °F")
except ValueError:
label_result.config(text="Invalid input!")

root = [Link]()
[Link]("Celsius to Fahrenheit")

[Link](root, text="Enter Celsius:").pack(pady=5)


entry_celsius = [Link](root)
entry_celsius.pack(pady=5)

[Link](root, text="Convert",
command=convert_temp).pack(pady=10)

label_result = [Link](root, text="Result: ")


label_result.pack(pady=5)

[Link]()
2. Construct a PyGame program that creates a 600x400 window. Inside 5 CO5 K3
it, draw a blue rectangle that moves from left to right continuously.
When it hits the right edge, it should reappear on the left.
import pygame

[Link]()
WIDTH, HEIGHT = 600, 400
screen = [Link].set_mode((WIDTH, HEIGHT))
[Link].set_caption("Moving Rectangle")

rect_color = (0, 0, 255) # Blue


rect_obj = [Link](0, 150, 50, 50) # x, y, width, height
58
running = True
while running:
for event in [Link]():
if [Link] == [Link]:
running = False

rect_obj.x += 5 # Move rectangle to the right


if rect_obj.left > WIDTH: # If it goes off the right edge
rect_obj.right = 0 # Move it back to the left edge

[Link]((0, 0, 0)) # Black background


[Link](screen, rect_color, rect_obj)
[Link]()

[Link]().tick(30) # Limit FPS

[Link]()
3. Build a PyGame Sprite class for a player character. The class should 5 CO5 K3
handle its initialization (__init__), its image ([Link]), its position
rectangle ([Link]), and include an update() method that moves the
sprite down by 5 pixels each time it's called.

import pygame

class Player([Link]):
def __init__(self):
# Call the parent class (Sprite) constructor
super().__init__()

# Create an image of the block, and fill it with a color.


[Link] = [Link]([50, 50])
[Link]((255, 0, 0)) # Red color

# Fetch the rectangle object that has the dimensions of the image
[Link] = [Link].get_rect()
[Link].x = 100
[Link].y = 100

def update(self):
# Move the sprite down by 5 pixels
[Link].y += 5
4. Outline the PyGame concepts used to model the following 5 CO5 K2
components in the "Angry Birds" case study: (a) The bird, (b) The
pigs, and (c) The slingshot mechanism. For each, mention the
specific PyGame features (e.g., sprites, physics, collision type)
employ.

(a) The Bird


The bird is a dynamic projectile modeled as a [Link]
class.

59
Physics: Its projectile motion (flight path) is simulated manually. This
is achieved by using [Link].Vector2 objects to represent the
bird's position, velocity, and a constant downward gravity vector. In
the sprite's update() method, velocity is modified by gravity each
frame, and position is updated by velocity.
Collision: [Link].collide_mask() is used for pixel-perfect
collision detection, which is accurate for the bird's non-rectangular
shape.
(b) The Pigs
The pigs are static targets that react to collisions.

Representation: Each pig is an instance of a [Link] and


all are managed within a [Link] for efficient collision
checking and rendering.
Collision & Reaction: [Link]() is used to detect
when the bird sprite hits any pig in the group. Upon collision, the pig
sprite is removed from the game by calling its [Link]() method.
(c) The Slingshot Mechanism
The slingshot is an interactive element combining visuals and user
input.

Visuals: The wooden frame is a static image, while the elastic bands
are drawn dynamically using [Link](). The lines connect
the slingshot frame to the bird's position, creating the visual effect of
stretching.
Interaction & Physics: The mechanism uses [Link].get_pos()
to track the drag position. When the mouse is released, a launch
vector is calculated (as a Vector2) based on the stretch distance and
direction. This vector is then assigned as the initial velocity for the
bird sprite, launching it.
5. A game records player scores in a MySQL table leaderboard with 5 CO5 K3
columns player_name (VARCHAR) and player_score (INT).
Develop a Python function add_score(name, score) that connects
to the database and inserts a new record. Include error handling
for database connection issues.
import [Link]
from [Link] import Error

def add_score(name, score):


"""
Connects to the MySQL database and inserts a new player
score.
Includes error handling for the connection and transaction.
"""
connection = None # Initialize connection to None
try:
# Establish the database connection (1 Mark)
connection = [Link](
host='localhost',
database='game_db',
user='your_username',
password='your_password'
)

60
if connection.is_connected():
cursor = [Link]()

# SQL INSERT statement with placeholders (2 Marks)


query = "INSERT INTO leaderboard (player_name,
player_score) VALUES (%s, %s)"
record = (name, score)
[Link](query, record)

# Commit the transaction to save the changes (1 Mark for


commit/close)
[Link]()
print(f"Record for {name} inserted successfully.")

except Error as e:
# Error handling block (1 Mark)
print(f"Error while connecting to MySQL or inserting data:
{e}")

finally:
# Ensure the connection is closed
if connection and connection.is_connected():
[Link]()
[Link]()
print("MySQL connection is closed.")
6. Discuss how sound is managed in PyGame. Explain the difference 5 CO5 K2
between background music (using the [Link] module) and
short sound effects (using the Sound object). Provide a brief code
example for each.

Sound Management in PyGame


In PyGame, sound is managed through the `[Link]`
module, which must be initialized with `[Link]()`. It
distinguishes between a single channel for continuous background
music and multiple channels for short, overlapping sound effects.

Background Music (`[Link]` module)


This module is designed to handle a single, streaming music
track, ideal for a game's soundtrack. It can play formats like MP3 and
OGG. Only one music track can be loaded and played at a time.

Key functions: `[Link]()`, `play()`, `stop()`,


`pause()`, `unpause()`, `set_volume()`.

Code Example
```python
import pygame
[Link]()
# Load and play background music, looping indefinitely
[Link]('soundtrack.mp3')
[Link](-1) # -1 means loop forever
```

61
Sound Effects (`Sound` object)
These are managed by creating `[Link]` objects, typically
from `.wav` files. Unlike background music, you can create many
`Sound` objects and play them simultaneously on different channels.
This is perfect for short, responsive sounds like jumps, explosions, or
collecting items.

Key functions:`[Link]()` to create an object, `.play()` to


trigger it, `.set_volume()`.

Code Example:
```python
import pygame
[Link]()
# Load a short sound effect
coin_sound = [Link]('coin_collect.wav')
# Play the sound effect when an event occurs
# if player_collects_coin:
# coin_sound.play()
7. Modify the following Tkinter code to include a top-level menu bar. 5 CO5 K3
The menu bar should have a "File" menu with two commands:
"New" (prints "New File") and "Exit" (closes the window).

import tkinter as tk

root = [Link]()
[Link]("My Editor")
[Link]("400x300")

def new_file_action():
print("New File")

# --- MODIFIED CODE STARTS HERE ---

# 1. Create the main menu bar (1 Mark)


main_menu = [Link](root)
[Link](menu=main_menu)

# 2. Create the "File" menu object (1 Mark)


file_menu = [Link](main_menu, tearoff=0) # tearoff=0
removes the dashed line

# 3. Add the "File" dropdown to the main menu bar


main_menu.add_cascade(label="File", menu=file_menu)

# 4. Add commands to the "File" menu


# "New" command (1.5 Marks)
file_menu.add_command(label="New",
command=new_file_action)
file_menu.add_separator() # Adds a visual line
62
# "Exit" command (1.5 Marks)
file_menu.add_command(label="Exit",
command=[Link])

# --- MODIFIED CODE ENDS HERE ---

[Link]()

8. Implement a custom event in PyGame. The event should be 5 CO5 K3


triggered every 2 seconds and cause a new enemy sprite to appear
at a random position at the top of the screen.

import pygame
import random

# Basic Enemy Sprite Class


class Enemy([Link]):
def __init__(self):
super().__init__()
[Link] = [Link]((30, 30))
[Link]((255, 0, 0)) # Red
[Link] = [Link].get_rect(
center=([Link](20, 780), -20)
# Start above screen
)
def update(self):
[Link].y += 3 # Move down
if [Link] > 600: [Link]()

[Link]()
screen = [Link].set_mode((800, 600))
enemies = [Link]()
all_sprites = [Link]()

# 1. Define a custom event ID (1 Mark)


ADD_ENEMY = [Link] + 1

# 2. Set a timer to trigger the event every 2000ms (2s) (1


Mark)
[Link].set_timer(ADD_ENEMY, 2000)

running = True
while running:
# 3. Event handling logic in the main loop (2 Marks)
for event in [Link]():
if [Link] == [Link]:
running = False
# Check for the custom event
elif [Link] == ADD_ENEMY:
# 4. Create and add a new enemy on
trigger (1 Mark)
new_enemy = Enemy()

63
[Link](new_enemy)
all_sprites.add(new_enemy)

all_sprites.update()
[Link]((0, 0, 0))
all_sprites.draw(screen)
[Link]()

[Link]()
9. Explain the role of a Sprite Group in PyGame. Demonstrate with 5 CO5 K2
a code snippet how you would create a group, add multiple sprite
instances to it, and then update and draw all sprites in the group
with single commands.

import pygame
# Assume a 'Block' sprite class exists
# class Block([Link]): ...

# 1. Create a group
all_sprites_group = [Link]()

# 2. Create and add multiple sprite instances


for i in range(5):
block = Block(color=(255,0,0), width=20, height=20)
[Link].x = i * 30
[Link].y = 100
all_sprites_group.add(block) # Add to the group

# In the main game loop:


# 3. Update all sprites in the group with one call
all_sprites_group.update()

# 4. Draw all sprites onto the screen with one call


all_sprites_group.draw(screen)
10. Design a Tkinter UI with a Frame containing two Radiobutton widgets 5 CO5 K3
(labeled "Play Sound" and "Mute") and one Scale widget (from 0 to
100). When the "Play Sound" radio button is active, moving the scale
should print its value (e.g., "Volume: 75"). When "Mute" is active, the
scale should do nothing.

import tkinter as tk

def on_scale_move(value):
# Check the state of the Radiobutton's control variable
if sound_mode.get() == "play":
print(f"Volume: {value}")

root = [Link]()
[Link]("Sound Control")

frame = [Link](root, relief="sunken", borderwidth=2)


64
[Link](padx=10, pady=10)

# Control variable for the radio buttons


sound_mode = [Link](value="play")

[Link](frame, text="Play Sound", variable=sound_mode,


value="play").pack(anchor=tk.W)
[Link](frame, text="Mute", variable=sound_mode,
value="mute").pack(anchor=tk.W)

# The scale's command is linked to the handler function


scale = [Link](frame, from_=0, to=100, orient=[Link],
length=200, command=on_scale_move)
[Link](75) # Set initial value
[Link](pady=10)

[Link]()

65

You might also like