0% found this document useful (0 votes)
21 views11 pages

Python Programming Exam Solutions 2024-25

The document provides solutions for the 'Python Programming' (BCC302) examination paper for the academic year 2024-25. It covers various topics including exception handling, basic calculator implementation, membership and identity operators, character frequency counting, file content reversal, and data visualization with matplotlib. Additionally, it discusses operator precedence, type conversion, email validation, and file modes in Python, along with practical programming examples.

Uploaded by

try.asmitt
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)
21 views11 pages

Python Programming Exam Solutions 2024-25

The document provides solutions for the 'Python Programming' (BCC302) examination paper for the academic year 2024-25. It covers various topics including exception handling, basic calculator implementation, membership and identity operators, character frequency counting, file content reversal, and data visualization with matplotlib. Additionally, it discusses operator precedence, type conversion, email validation, and file modes in Python, along with practical programming examples.

Uploaded by

try.asmitt
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

Here are the solutions for the "Python Programming" (BCC302) examination

paper(2024-25)

SECTION A
(Attempt all questions in brief - 2 Marks each)

a. State how to handle exceptions in Python? Provide a simple example.

In Python, exceptions are handled using try, except, else, and finally blocks. The code that
might raise an error is placed inside the try block, and the code to handle the error is placed
in the except block2.

●​ Example:
●​ Python

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
●​
●​

b. What will be the output of the following Python code?

Python

def compute(x):
return [i**2 for i in x if i%2==0] # Corrected syntax from image
print(compute([1, 2, 3, 4, 5]))

●​ Logic: The list comprehension iterates through the input list [1, 2, 3, 4, 5]. It filters for
even numbers (if i%2==0): 2 and 4. Then it squares them (i**2): $2^2 = 4$ and $4^2
= 16$.
3
●​ Output: [4, 16] .

c. Explain floor division with an example.

Floor division is performed using the // operator. It divides two numbers and rounds the result
down to the nearest whole integer, discarding any decimal remainder4.

●​ Example:
●​ Python
print(10 // 3) # Output: 3 (3.33 rounded down)
print(-10 // 3) # Output: -4 (-3.33 rounded down to -4)
●​
●​

d. Describe the purpose of the 'with' statement in file handling?

The with statement simplifies file handling by automatically managing resources. It ensures
that the file is properly closed after the block of code is executed, even if an exception
occurs during the process. This prevents memory leaks5.

e. Briefly describe the use of lambda functions in Python.

Lambda functions are small, anonymous functions defined with the keyword lambda. They
can take any number of arguments but can only have one expression. They are typically
used for short, throwaway functions (e.g., inside map(), filter(), or sorted())6.

●​ Syntax: lambda arguments: expression

f. Demonstrate how to assign a single value to a tuple.

To create a tuple with a single element, you must include a comma after the value. Without
the comma, Python interprets it as a standard variable (int, str, etc.) inside parentheses7.

●​ Example:
●​ Python

t = (5,) # This is a tuple


print(type(t)) # <class 'tuple'>
●​
●​

g. Explain why numpy is used instead of python arrays for mathematical calculations?

NumPy is used because:

1.​ Speed: NumPy arrays are significantly faster than Python lists because they are
implemented in C and use contiguous memory.
2.​ Functionality: It provides a vast library of high-level mathematical functions (linear
algebra, Fourier transforms, etc.) that operate on arrays efficiently.
8
3.​ Memory: NumPy arrays use less memory than Python lists .

SECTION B
(Attempt any three - 7 Marks each)
2a. Design a basic calculator in Python that supports addition, subtraction,
91011
multiplication, division.

Python

def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice(1/2/3/4): ")

if choice in ['1', '2', '3', '4']:


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Error! Division by zero.")
else:
print("Invalid Input")

calculator()

This program defines a function that takes user input for an operation and two numbers, then
12
performs the corresponding arithmetic using if-elif-else logic .

2b. Distinguish between Membership and Identity Operators. Given a=3, b=3, explain
(a is b) and (a==b).
●​ Membership Operators (in, not in): Test if a sequence (like a string, list, or tuple)
contains a specific object.
○​ Example: 3 in [1, 2, 3] returns True.
●​ Identity Operators (is, is not): Compare the memory location of two objects. They
return True if both variables point to the exact same object in memory.
●​ The Case of a=3, b=3:
○​ a == b: Checks if the values are equal. Since 3 equals 3, this returns True.
○​ a is b: Checks if a and b refer to the same object. In Python, small integers
(typically -5 to 256) are cached and reused (interning). Therefore, a and b
point to the same memory address for the integer 3. This returns True.

2c. Write a Python function to count the frequency of each character in a given string
and return the output in a dictionary.

Python

def char_frequency(s):
freq_dict = {}
for char in s:
if char in freq_dict:
freq_dict[char] += 1
else:
freq_dict[char] = 1
return freq_dict

# Example Usage
print(char_frequency("HELLO"))
# Output: {'H': 1, 'E': 1, 'L': 2, 'O': 1}

This function iterates through the string. If a character is already a key in the dictionary, it
13
increments the count; otherwise, it initializes the count to 1 .

2d. Write a program to reverse the contents of a file character by character, separating each
character with a comma.

(Assuming the goal is to read a file, process it, and print/save the reversed
comma-separated version)

Python

def reverse_file_content(filename):
try:
with open(filename, 'r') as file:
content = [Link]()

# Reverse the content


reversed_content = content[::-1]

# Join characters with comma


result = ",".join(list(reversed_content))

print(result)

except FileNotFoundError:
print("File not found.")

# Usage: Create a dummy file first to test


with open("[Link]", "w") as f:
[Link]("HELLO")

reverse_file_content("[Link]")
# Output: O,L,L,E,H

14

2e. Create a pie chart using matplotlib to represent the following data: Languages
Popularity.

Python

import [Link] as plt

# Data
languages = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby']
popularity = [30, 25, 20, 15, 10]

# Creating the pie chart


[Link](figsize=(8, 8))
[Link](popularity, labels=languages, autopct='%1.1f%%', startangle=140)

# Title
[Link]('Programming Languages Popularity')

# Show plot
[Link]()

The code uses [Link]() to generate the chart, with labels for the legend and autopct to
15151515
display percentages .

SECTION C
(Attempt anyone part from each question - 7 Marks each)

Question 3
a. Write short notes on: Operator Precedence, Python Indentation, Type Conversion.
1.​ Operator Precedence: This determines the order in which operations are evaluated
in an expression. For example, multiplication * has higher precedence than addition
+. 2 + 3 * 4 equals 14 (not 20) because 3*4 happens first. Parentheses () have the
highest precedence.
2.​ Python Indentation: Unlike many languages that use braces {}, Python uses
whitespace (indentation) to define blocks of code (loops, functions, classes). Correct
indentation is mandatory; inconsistent indentation raises an IndentationError. It
improves readability.
3.​ Type Conversion (Type Casting): The process of converting a variable from one
data type to another.
○​ Implicit: Python automatically converts types (e.g., adding int and float results
in float).
○​ Explicit: The user manually converts types using functions like int(), float(),
1616
str() .

OR

b. Write a program to validate email addresses using regular expressions.

Criteria: Must contain @, domain name, and no spaces.

Python

import re

def validate_email(email):
# Regex Explanation:
#^ : Start of string
# [^@\s]+ : One or more characters that are NOT @ or space
#@ : Literal @ symbol
# [^@\s]+ : Domain name (characters NOT @ or space)
# \. : Literal dot
# [^@\s]+ : TLD (characters NOT @ or space)
#$ : End of string
pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"

if [Link](pattern, email):
print(f"'{email}' is Valid")
else:
print(f"'{email}' is Invalid")

# Test Cases
validate_email("student@[Link]")
validate_email("student @[Link]") # Invalid (space)
validate_email("[Link]") # Invalid (no @)

17171717

Question 4
a. Write a program to create a hollow pyramid pattern.

Python

def hollow_pyramid(n):
for i in range(1, n + 1):
# Print leading spaces
print(" " * (n - i), end="")

# Logic for stars


if i == 1:
print("*")
elif i == n:
print("*" * (2 * i - 1))
else:
# Print star, spaces, then star
print("*", end="")
print(" " * (2 * i - 3), end="")
print("*")

# Example Usage
hollow_pyramid(5)

Output for n=5:

Plaintext

*
**
**
**
*********

18

OR

b. Explain why loops are needed and types of loops. Discuss break and continue.
●​ Why Loops? Loops are used to execute a block of code repeatedly until a specific
condition is met. They reduce code redundancy and handle tasks like iterating
through data structures or repeating actions.
●​ Types of Loops:
○​ for loop: Used for iterating over a sequence (list, tuple, string, range).
○​ while loop: Repeats as long as a boolean condition is true.
●​ Control Statements:
○​ break: Terminates the loop immediately.
■​ Example: Stop searching when an item is found.
○​ continue: Skips the current iteration and jumps to the next one.
19
■​ Example: Skip printing odd numbers in a loop .

Question 5
a. Write a function to find the longest word in a given list of words.

Python

def longest_word(word_list):
if not word_list:
return None

longest = ""
for word in word_list:
if len(word) > len(longest):
longest = word

return longest

# Example
words = ['apple', 'banana', 'cherry']
print(longest_word(words))
# Output: 'banana'

20

OR

b. Distinguish between a Tuple and a List. Explain 4 built-in Dictionary methods.


●​ Tuple vs List:
1.​ Mutability: Lists are mutable (can be changed); Tuples are immutable
(cannot be changed after creation).
2.​ Syntax: Lists use []; Tuples use ().
3.​ Performance: Tuples are slightly faster due to immutability.
●​ Dictionary Methods:
1.​ keys(): Returns a view object containing the keys of the dictionary.
2.​ values(): Returns a view object containing the values.
3.​ items(): Returns a list of tuple pairs (key, value).
4.​ get(key): Returns the value for a key if it exists, otherwise returns None
21
(avoids errors) .

Question 6
a. Discuss different types of file modes in Python? Explain with examples.

File modes determine how a file is opened.

1.​ 'r' (Read): Default. Opens for reading. Error if file doesn't exist.
2.​ 'w' (Write): Opens for writing. Creates a new file or truncates (deletes content of)
existing file.
3.​ 'a' (Append): Opens for writing. Creates file if not exists; adds data to the end
without deleting old content.
4.​ 'r+' (Read+Write): Opens for both reading and writing.
22
○​ Example: f = open("[Link]", "w") creates a file for writing .

OR

b. Program to read CSV and display rows where a column exceeds a threshold.

Python

import csv

def filter_csv(filename, col_index, threshold):


try:
with open(filename, 'r') as file:
reader = [Link](file)
header = next(reader) # Skip header
print(f"Header: {header}")

for row in reader:


# Convert column value to float/int for comparison
try:
val = float(row[col_index])
if val > threshold:
print(row)
except ValueError:
continue # Skip if value isn't a number

except FileNotFoundError:
print("File not found")

# Usage (Assuming column 1 is numeric and we want values > 50)


# filter_csv('[Link]', 1, 50)

23

Question 7
a. Discuss role of event handling in Tkinter. How to bind events?
Event handling allows the application to respond to user actions (clicks, key presses).

●​ Binding: You connect an event (like <Button-1> for left click) to a function (handler)
using the [Link]() method.
●​ Example:
●​ Python

import tkinter as tk

def on_click(event):
print("Button clicked!")

root = [Link]()
btn = [Link](root, text="Click Me")
[Link]("<Button-1>", on_click) # Bind left click to function
[Link]()
[Link]()
●​
●​

24

OR

b. Program to read '[Link]', calculate average marks, and display results.

Assumption: CSV format is Name, Mark1, Mark2, ...

Python

import csv

def calculate_average(filename):
try:
with open(filename, 'r') as file:
reader = [Link](file)
header = next(reader) # Skip header if exists

print(f"{'Name':<15} {'Average':<10}")
print("-" * 25)

for row in reader:


name = row[0]
# marks are from index 1 to end
marks = [float(x) for x in row[1:]]

if marks:
avg = sum(marks) / len(marks)
print(f"{name:<15} {avg:.2f}")

except Exception as e:
print(f"Error: {e}")

# Usage
# calculate_average('[Link]')

You might also like