Python Programming Question Bank
Python Programming Question Bank
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.
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:
name = "John"
age = 25
height = 5.9
length = 10
2
breadth = 5
area = length * breadth
print("Area =", area)
Expected Output:
Area = 50
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
def greet(name):
print("Hello", name)
greet("Ravi")
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.
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.
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)
# 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
# Sample dictionary
student_scores = {
"Aravind": 85,
"Bhavya": 92,
"Deepak": 76
}
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.
# Total bill
total = meal_price + tip + gst
10
Packages help organize code into logical, hierarchical structures
and enable better modularity, scalability, and reuse.
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
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)]
11
import pandas as pd
# pandas is a powerful module for data analysis
# Write to CSV
df.to_csv("students_pandas.csv", index=False)
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
Syntax:
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")
]
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)
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.
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)
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
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])
@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:
Key functions:
Example Program:
import os
import sys
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
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.
Drawback:
● Uses more memory (data stores all lines at once).
● Inefficient for very large files.
● May cause MemoryError on low-RAM systems.
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.
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'
● 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"
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"
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)
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 = []
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:
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.
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
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
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
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.
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)
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'
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.
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
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.
Use try-except-else-finally.2m
34
t2 = [Link](target=greet, args=("Thread-2",))
t3 = [Link](target=greet, args=("Thread-3",))
35
[Link]()
[Link]()
[Link]()
# Input
input_str = input("Enter numbers separated by space:\n")
numbers = list(map(int, input_str.strip().split()))
mid = len(numbers) // 2
first_half = numbers[:mid]
second_half = numbers[mid:]
36
t2 = [Link](target=compute_sum, args=(second_half, 1))
# Start threads
[Link]()
[Link]()
# 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
left = phil_id
right = (phil_id + 1) % NUM_PHILOSOPHERS
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))
chopsticks[left].release()
print(f"Philosopher {phil_id} put down left chopstick")
38
[Link](t)
[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
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
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
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
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
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.
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.
import numpy as np
print([Link]) # Output: 2
print([Link]) # Output: 4
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:
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.
1. Integer Indexing
� Example:
import numpy as np
45
[90, 100, 110, 120]])
2. Boolean Indexing
� Example:
filtered_elements = array[condition]
Array Slicing
� Example:
[5, 6, 7, 8],
46
# Slicing rows 0 and 1, and columns 1 and 2
print(subset)
# Output:
# [[2 3]
# [6 7]]
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
47
We can visualize both the original data and the rolling mean using
[Link].
[Link]()
mean_marks = df['Marks'].mean()
48
median_marks = df['Marks'].median()
std_marks = df['Marks'].std()
print("Mean:", mean_marks)
print("Median:", median_marks)
df['Marks'].describe()
This returns count, mean, std, min, 25%, 50% (median), 75%, and
max values.
This creates a new DataFrame with only rows where 'Age' > 30.
Method:
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.
49
Most data points are clustered at the lower end of the scale.
Example:
Income distribution: Most people earn between ₹20k–₹80k/month,
but a few earn ₹5L–₹10L/month.
Numerical Indicators:
Mean > Median > Mode
� 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.
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.
Poor scaling:
50
In charts, skew can cause most values to appear bunched together,
hiding variation.
Wrong assumptions:
[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.
51
[Link]("Log(Frequency)")
[Link](True)
[Link]() ng how we interpret the data.
� 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:
Program:
import numpy as np
a = [Link]([1, 2])
b = [Link]([4, 6])
print("Array-1")
print(a)
print("\nArray-2")
print(b)
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
import cv2
import numpy as np
import pandas as pd
Output:
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
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.
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="Convert",
command=convert_temp).pack(pady=10)
[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")
[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__()
# 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.
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.
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
60
if connection.is_connected():
cursor = [Link]()
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.
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.
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")
[Link]()
import pygame
import random
[Link]()
screen = [Link].set_mode((800, 600))
enemies = [Link]()
all_sprites = [Link]()
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]()
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")
[Link]()
65