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

Python Solution

The document is a solution set for a Python programming exam covering various topics including exception handling, lambda functions, file handling, loops, and data structures. It provides code examples for concepts like operator precedence, type conversion, and event handling in Tkinter. Additionally, it includes exercises for creating a calculator, counting character frequency, and generating a pie chart using matplotlib.

Uploaded by

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

Python Solution

The document is a solution set for a Python programming exam covering various topics including exception handling, lambda functions, file handling, loops, and data structures. It provides code examples for concepts like operator precedence, type conversion, and event handling in Tkinter. Additionally, it includes exercises for creating a calculator, counting character frequency, and generating a pie chart using matplotlib.

Uploaded by

zeeshan.ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

BTECH (SEM III) THEORY EXAMINATION 2024-25 PYTHON PROGRAMMING SOLUTION SET

SUBJECT CODE - BCC 302

SECTION A
a. State how to handle exceptions in Python? Provide a simple example.
try:
x = 10 / 0
except ZeroDivisionError: print("Cannot divide by
zero!")

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


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

print(compute([1, 2, 3, 4, 5]))
# Output: [4, 16]
c. Explain floor division with an example
x=7
y=2
print(x // y) # Output: 3

The values after the decimal are truncated in floor division.


d.
The 'with' statement is used to ensure proper acquisition and release of resources. It is majorly used in
File handling with the open function.
with open("example.txt", "r") as file: content =
file.read()
e. Briefly describe the use of lambda functions in Python.
Lambda functions are anonymous, small functions defined using the lambda keyword. They can have
any number of arguments but only one expression. They are commonly used for short, throwaway
functions that are passed as arguments to higher-order functions like map(), filter(), and sorted().

Example:

# Lambda function to square a number square =

lambda x: x ** 2 print(square(4)) # Output: 16

Lambda functions are useful when a simple function is needed temporarily and doesn't require a formal
definition using def
f. Demonstrate how to assign a single value to a tuple.
t = (5,) # Comma makes it a tuple. If comma is not inserted, it is normally an assignment of a string
value to a variable.

g. Explain why numpy is used instead of python arrays for mathematical calculations?
NumPy is used because it provides powerful, efficient, and optimized array operations. Unlike Python
lists, NumPy arrays consume less memory, support vectorized operations (no need for loops), and offer
a wide range of mathematical functions, making calculations faster and more convenient.

Example:

import numpy as np a =

np.array([1, 2, 3])

print(a * 2) # Output: [2 4 6]

In contrast, multiplying a Python list by 2 would repeat the list: 2, 3]


SECTION B

a. Design a basic calculator in Python that supports addition, subtraction,


multiplication, division.
a = int(input("Enter first number: "))
b = int(input("Enter second number: ")) op =
input("Enter operator (+, -, *, /): ")

if op == '+': print(a + b)
elif op == '-': print(a - b) elif
op == '*': print(a * b)
elif op == '/': print(a / b)
else:
print("Invalid operator")

b. Define Membership and Identity Operators. Given:


a=3
b=3
Distinguish between: (a is b) and (a = = b) ? Membership
Operators

Membership Operators:
Membership operators are used to test whether a value is a member of a sequence (like a string, list, tuple,
etc.).
There are two membership operators in Python:

1. in: Returns True if a value is found in the sequence.


2. not in: Returns True if a value is not found in the sequence.
Example:
my_list = [1, 2, 3, 4]
print(2 in my_list) # Output: True print(5 not in
my_list) # Output: True
Identity Operators

Identity Operators:

Identity operators are used to compare the memory locations of two objects. They determine
whether two variables refer to the same object in memory.

There are two identity operators in Python:

1. is: Returns True if both variables point to the same object.


2. is not: Returns True if they point to different objects.
Given:
a=3
b=3
Comparison:
(a == b): This checks if the values of a and b are equal. Returns True.
(a is b): This checks if a and b refer to the same object in memory. Returns True for small integers
because of Python's internal caching.

Example:
a=3
b=3
print(a == b) # Output: True (values are equal)
print(a is b) # Output: True (both refer to the same memory object) However, this behavior

may differ for larger or mutable objects.

Example:
x = [1, 2]
y = [1, 2]
print(x == y) # Output: True (values are equal)
print(x is y) # Output: False (different memory locations)

c. Write a Python function to count the frequency of each character in a given string
and return the output in a dictionary. Example: char_frequency("HELLO") returns
{"H":1, "E":1, "L":2, "O":1}
def char_frequency(s): freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1 return freq
print(char_frequency("HELLO"))
# Output: {'H': 1, 'E': 1, 'L': 2, 'O': 1}

d. Write a program to reverse the contents of a file character by character, separating


each character with a comma.
with open("file.txt", "r") as file: content =
file.read()
reversed_content = ",".join(reversed(content))
print(reversed_content)
e. Create a pie chart using matplotlib to represent the following data:

import matplotlib.pyplot as plt


labels = ['Python', 'Java', 'C++', 'JavaScript', 'Ruby'] sizes = [30,
25, 20, 15, 10]

plt.pie(sizes, labels=labels, autopct='%1.1f%%')


plt.title("Languages Popularity")
plt.show()
SECTION C

3.a. Write short notes on the following with examples:


a) Operator Precedence
b) Python Indentation
c) Type Conversion

a) Operator Precedence
Operator precedence defines the order in which different operators in an expression are evaluated.
Python evaluates expressions from left to right, but operators with higher precedence are evaluated before
those with lower precedence.
For example:
result = 10 + 2 * 5 print(result) # Output: 20
Explanation:
Multiplication (*) has higher precedence than addition (+), so 2 * 5 is evaluated first, resulting in 10.
Then 10 + 10 gives 20.

Common Operator Precedence (High to Low):


1. Parentheses: ()
2. Exponentiation: **
3. Multiplication, Division, Floor Division, Modulus: *, /, //, %
4. Addition and Subtraction: +, -
5. Comparison Operators: >, <, ==, etc.
6. Logical Operators: and, or, not

b) Python Indentation
Indentation in Python is very important as it defines the block of code. Unlike other programming languages
that use curly braces,
Python uses indentation (spaces or tabs) to indicate a block of code.
For example: if 5 > 2:
print("Five is greater than two")

Explanation:
The print statement is indented, indicating that it belongs to the if block. If indentation is
not used correctly, Python will raise an IndentationError.

Proper indentation helps maintain code readability and structure.

c) Type Conversion
Type conversion refers to converting one data type into another. It is of two types: implicit and explicit.

1. Implicit Type Conversion:


Automatically performed by Python. Example:
result = 3 + 4.5 print(result) # Output:
7.5
Here, integer 3 is automatically converted to float before addition.
2. Explicit Type Conversion:
Done manually by the programmer using functions like int(), float(), str(), etc. Example:
num_str = "100" num_int =
int(num_str)
print(num_int + 50) # Output: 150
Type conversion is useful when performing operations involving mixed data types.

3.b. Write a program to validate email addresses using regular expressions. Criteria:
1. Must contain @ symbol
2. Must contain domain name
3. Should not have spaces
import re
email = input("Enter email: ")
pattern = r'^[^\s@]+@[^\s@]+\.[^\s@]+$'
if re.match(pattern, email): print("Valid
Email")
else:
print("Invalid Email")
4. a. Write a program to create a hollow pyramid pattern given below:
*
* *
* *
* *
*********
rows = 5
for i in range(rows): for j in range(i +
1):
if j == 0 or j == i or i == rows - 1: print("*",
end="")
else:
print(" ", end="") print()

4.b. Explain the why loops are needed and the types of loops in python. Discuss break
and continue with example.
Loops in Python: Loops are used in Python to execute a block of code repeatedly as long as a certain
condition is met.
They help in reducing code redundancy, improving efficiency, and performing repetitive tasks like
traversing a list,
processing user input, or executing a set of instructions multiple times.
Python provides two main types of loops:
1. for loop
2. while loop

1) for Loop
Used to iterate over a sequence (like a list, tuple, string, or range).
Example:
for i in range(5): print(i)

Output: 0
1
2
3
4
Explanation: The loop runs 5 times and prints numbers from 0 to 4.
2) while Loop
Executes a block of code as long as a specified condition is true.

Example: i = 0
while i < 5: print(i)
i += 1
Output: 0
1
2
3
4
Explanation: The loop continues to execute as long as i is less than 5.
Break and Continue Statements
1. break Statement:
Used to exit the loop prematurely when a condition is met.
Example:
for i in range(10): if i == 5:
break print(i)
Output: 0
1
2
3
4
Explanation: The loop stops when i equals 5.
2. continue Statement:
Skips the current iteration and continues with the next one.

Example:
for i in range(5):
if i == 2: continue
print(i)
Output: 0
1
3
4
Explanation: When i is 2, the print statement is skipped and the loop continues.
# Looping example for i in
range(5):
if i == 2: continue
if i == 4: break
print(i)

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

def longest_word(words): return max(words,


key=len)
print(longest_word(['apple', 'banana', 'cherry'])) # Output:
'banana'

5.b. Distinguish between a Tuple and a List with examples. Explain with examples
atleast 4 built-in methods of Dictionary.
Tuple vs List in Python

In Python, both tuples and lists are used to store collections of items. However, there are several key
differences between them.

Here is a comparison between tuples and lists:


Feature Tuple List

Mutability Immutable Mutable


Syntax tuple1 = (1, 2, 3) list1 = [1, 2, 3]

Performance Faster than lists Slightly slower

Use Case Fixed collections of items Collections that may


change
Example:

# Tuple example tuple1 = (1, 2, 3)


# tuple1[0] = 10 # This will raise an error

# List example list1 = [1, 2, 3]


list1[0] = 10 # This is allowed print(list1)

Built-in Dictionary Methods with Examples

Python provides several built-in methods to work with dictionaries. Here are four commonly used ones:

1. get()

Returns the value for the specified key if key is in dictionary.

my_dict = {'name': 'Alice', 'age': 25} print(my_dict.get('name')) # Output:


Alice print(my_dict.get('city', 'Not Found')) # Output: Not Found

2. keys()

Returns a view object that displays a list of all the keys in the dictionary.

my_dict = {'name': 'Alice', 'age': 25} print(my_dict.keys()) # Output:


dict_keys(['name', 'age'])

3. values()

Returns a view object that displays a list of all the values in the dictionary.

my_dict = {'name': 'Alice', 'age': 25} print(my_dict.values()) # Output:


dict_values(['Alice', 25])

4. items()

Returns a view object that displays a list of dictionary's key-value tuple pairs.
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 25)])

6.a. Discuss different types of file modes in Python? Explain with examples.
In Python, file handling is done using the built-in open() function. When opening a file, we need to
specify the mode in which we want to access the file such as reading, writing, or
appending. These modes determine the operations we can perform on the file.

Syntax:

file = open("filename", "mode")

Types of File Modes Read Mode


('r')

Opens the file for reading. Raises FileNotFoundError if the file does not exist.

file = open("example.txt", "r") content =


file.read() print(content)
file.close()

Write Mode ('w')

Opens the file for writing. Overwrites existing content or creates a new file if it doesn't exist.

file = open("example.txt", "w")


file.write("Hello, world!") file.close()

Append Mode ('a')

Opens the file for appending. Creates the file if it does not exist.

file = open("example.txt", "a") file.write("\nThis is


a new line.") file.close()

Read and Write Mode ('r+')

Opens the file for both reading and writing. File must already exist.
file = open("example.txt", "r+") print(file.read())
file.write("\nAdded text.") file.close()

Write and Read Mode ('w+')

Opens the file for writing and reading. Overwrites the file or creates a new one.

file = open("example.txt", "w+") file.write("New


content.") file.seek(0)
print(file.read()) file.close()

Append and Read Mode ('a+')

Opens the file for appending and reading. File pointer is at the end.

file = open("example.txt", "a+") file.write("\nMore


content.") file.seek(0)
print(file.read()) file.close()

Binary Modes

Used for non-text files. Add 'b' with modes like 'rb', 'wb', 'ab', etc.

file = open("image.jpg", "rb") data =


file.read()
file.close()
6.b. Write a program to read a CSV file and display the rows where a specific
column value exceeds a given threshold.
import csv
threshold = 50
with open("students.csv", "r") as file: reader =
csv.DictReader(file)
for row in reader:
if int(row["marks"]) > threshold: print(row)
7.a. Discuss the role of event handling in Tkinter. How can you bind events to widgets?
Provide examples.

crucial part of any GUI application. It allows the program to respond to user interactions like mouse
clicks, key presses, and other actions. In Tkinter, this is done by binding functions (event handlers) to
specific events.

Role of Event Handling

Event handling in Tkinter allows developers to define how the application should respond to user
interactions. Whenever an event occurs such as a button click or a key press
the corresponding event handler function is executed. This makes the application interactive and
dynamic.

Binding Events to Widgets

In Tkinter, events are bound to widgets using the `bind()` method or through widget- specific options
like `command` in Buttons.

Syntax using bind():

widget.bind("<event>", handler_function)

Common events include:

- `<Button-1>`: Left mouse click


- `<Button-2>`: Middle mouse click
- `<Button-3>`: Right mouse click
- `<Double-Button-1>`: Double click
- `<Key>`: Any key press
- `<Return>`: Enter key press

Examples

Example 1: Binding a Mouse Click

This example binds a left mouse click event to a label. When the label is clicked, a message is printed.

from tkinter import Tk, Label

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


root = Tk()
label = Label(root, text="Click me!") label.pack()
label.bind("<Button-1>", on_click)
root.mainloop()

Example 2: Using command with Button

This is a simpler method for buttons, where we use the `command` option to bind a function to a click
event.

from tkinter import Tk, Button


def say_hello(): print("Hello!")
root = Tk()
button = Button(root, text="Greet", command=say_hello) button.pack()
root.mainloop()
7.b. Write a program to read data from a CSV file 'students.csv', calculate the average
marks for each student, and display the results.
import csv

with open("students.csv", "r") as file: reader =


csv.DictReader(file)
for row in reader:
marks = list(map(int, row['marks'].split(','))) avg =
sum(marks) / len(marks) print(f"{row['name']}: {avg}")

You might also like