You are on page 1of 10

21(a)You can achieve this by defining the function `showGrades` as follows:

def showGrades(S):

for name, scores in S.items():

average_score = sum(scores) / len(scores)

if average_score > 90:

grade = "A"

elif average_score >= 60:

grade = "B"

else:

grade = "C"

print(f"{name} {grade}")

# Test the function with the given dictionary

S = {"AMIT": [92, 86, 64], "NAGMA": [65, 42, 43], "DAVID": [92, 90, 85]}

showGrades(S)

This function iterates through the dictionary `S`, calculates the average score for each student, and
assigns a grade based on the given rules. Finally, it prints the student's name along with their
corresponding grade.

23(a)Here's a Python function named `Puzzle` that accomplishes the task:

def Puzzle(W, N):

result = ''

for i, char in enumerate(W):

if (i + 1) % N == 0:

result += '_'

else:

result += char

return result
# Test the function

word = "TELEVISION"

N=3

print(Puzzle(word, N)) # Output: TE_EV_SI N

N=4

print(Puzzle(word, N)) # Output: TEL VIS ON

This function iterates through each character in the word and replaces every Nth character with an
underscore. Then it returns the modified string.

23(a)Here are the Python commands to convert the tuple to a list and delete the last element:

# Given tuple

subject = ('Math', 'Science', 'History', 'English')

# Convert tuple to list

subject_list = list(subject)

# Delete the last element of the list

del subject_list[-1]

# Print the modified list

print(subject_list)

Output:

['Math', 'Science', 'History']

Explanation:

1. `list(subject)` converts the tuple `subject` to a list and assigns it to the variable `subject_list`.

2. `del subject_list[-1]` deletes the last element of the list `subject_list`.

3. Finally, the modified list `subject_list` is printed.

28.(A) Here's a Python function named `showInLines()` to achieve this task:


def showInLines():

try:

# Open the file STORY.TXT in read mode

with open("STORY.TXT", "r") as file:

# Read the contents of the file

content = file.read()

# Split the content into sentences based on '.', '?', and '!'

sentences = content.split(".")
sentences = [sentence.strip() for sentence in sentences if sentence.strip()] # Remove empty string
s

# If there are no sentences ending with '.', try splitting based on '?'

if not sentences:

sentences = content.split("?")

sentences = [sentence.strip() for sentence in sentences if sentence.strip()]

# If there are still no sentences, split based on '!'

if not sentences:

sentences = content.split("!")

sentences = [sentence.strip() for sentence in sentences if sentence.strip()

# Display each sentence on a separate line

for sentence in sentences:

print(sentence.strip() + ".") # Add '.' back to the end of each sentence

except FileNotFoundError:

print("File STORY.TXT not found.")

# Call the function to display the content of the file in separate lines

showInLines()

This function reads the content of the file "STORY.TXT", splits it into sentences based on '.', '?', and '!',
and then displays each sentence on a separate line. If the file is not found, it prints a message indicating
the same.
28(b) here's a Python function `c_words()` that counts and displays the number of uppercase and
lowercase alphabets in a text file named "Words.txt":

def c_words():

try:

# Open the file Words.txt in read mode

with open("Words.txt", "r") as file:

# Read the contents of the file

content = file.read()

# Initialize counters for uppercase and lowercase alphabets

uppercase_count = 0

lowercase_count = 0

# Loop through each character in the content

for char in content:

# Check if the character is an uppercase alphabet

if char.isupper():

uppercase_count += 1

# Check if the character is a lowercase alphabet

elif char.islower():

lowercase_count += 1

# Display the counts

print("Number of uppercase alphabets:", uppercase_count)

print("Number of lowercase alphabets:", lowercase_count)

except FileNotFoundError:

print("File Words.txt not found.")

# Call the function to count and display the number of uppercase and lowercase alphabets
c_words()

This function reads the content of the file "Words.txt", counts the number of uppercase and lowercase
alphabets separately, and then displays the counts. If the file is not found, it prints a message indicating
the same.

30(a) here's the implementation of the described functions:

class Stack:

def __init__(self):

self.items = []

def push(self, item):

self.items.append(item)

def pop(self):

if not self.is_empty():

return self.items.pop()

def is_empty(self):

return len(self.items) == 0

def PushBig(Nums, BigNums):

for num in Nums:

if len(str(num)) >= 5:

BigNums.push(num)

def PopBig(BigNums):

while not BigNums.is_empty():

print(BigNums.pop())

else:
print("Stack Empty")

# Example usage:

Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]

BigNums = Stack()

# Push numbers with 5 or more digits into BigNums stack

PushBig(Nums, BigNums)

# Pop numbers from BigNums stack and display them

PopBig(BigNums)

This code defines a `Stack` class to implement a stack data structure. Then, it defines `PushBig()` and
`PopBig()` functions as described. Finally, it demonstrates the usage of these functions with an example
list `Nums`.

32. Here's the implementation of the described functions:

import csv

def Add_Device():

try:

with open("Peripheral.csv", "a", newline='') as file:

writer = csv.writer(file)

P_id = int(input("Enter Peripheral device ID: "))

P_name = input("Enter Peripheral device name: ")

Price = int(input("Enter Peripheral device price: "))

writer.writerow([P_id, P_name, Price])

print("Record added successfully!")

except FileNotFoundError:

print("Peripheral.csv file not found.")


def Count_Device():

try:

count = 0

with open("Peripheral.csv", "r") as file:

reader = csv.reader(file)

next(reader) # Skip the header row

for row in reader:

if int(row[2]) < 1000:

count += 1

print("Number of peripheral devices with price less than 1000:", count)

except FileNotFoundError:

print("Peripheral.csv file not found.")

# Example usage:

Add_Device()

Count_Device()

Explanation:

- `Add_Device()` function prompts the user to enter details for a peripheral device (ID, name, and price)
and appends this record to the "Peripheral.csv" file using the `csv.writer` module.

- `Count_Device()` function opens the "Peripheral.csv" file, reads each record using `csv.reader`, and
counts the number of peripheral devices with a price less than 1000.

- In both functions, exception handling is used to catch the `FileNotFoundError` if the "Peripheral.csv" file
is not found.

34.(A) Here's how you can implement the `Copy_new()` function to achieve the described task:

import pickle

def Copy_new():

try:
# Open items.dat for reading in binary mode

with open("items.dat", "rb") as file:

# Open new_items.dat for writing in binary mode

with open("new_items.dat", "wb") as new_file:

# Iterate through each record in items.dat

while True:

try:

# Unpickle each record from items.dat

record = pickle.load(file)

# Check if the amount is greater than 1000

if record['amount'] > 1000:

# Pickle and write the record to new_items.dat

pickle.dump(record, new_file)

except EOFError:

break # End of file reached

print("Copying completed successfully!")

except FileNotFoundError:

print("File items.dat not found.")

# Example usage:

Copy_new()

Explanation:

- The `Copy_new()` function opens the binary file "items.dat" for reading and "new_items.dat" for
writing in binary mode.

- It iterates through each record in "items.dat" using a while loop.

- For each record, it unpickles the record, checks if the amount is greater than 1000, and if so, pickles
and writes the record to "new_items.dat".

- The process continues until the end of the file is reached (EOFError).

- Exception handling is used to catch the FileNotFoundError if "items.dat" is not found.


- Once all records are copied, it prints a message indicating successful completion

34(a) here how you can implement the `disp_Detail()` function to achieve the described task:

import struct

def disp_Detail():

try:

with open("EMP.DAT", "rb") as file:

while True:

# Read one record (16 bytes) from the binary file

record = file.read(16)

# If the record is empty, end of file is reached

if not record:

break

# Unpack the binary data into individual fields (Emp_Id, Name, Salary)

emp_id, name, salary = struct.unpack("10s 10s f", record)

# Decode bytes to string and strip trailing spaces

name = name.decode().strip()

# Check if salary is below 25000

if salary < 25000:

print(f"Emp_Id: {emp_id.decode()}, Name: {name}, Salary: {salary}")

except FileNotFoundError:

print("File EMP.DAT not found.")

# Example usage:

disp_Detail()

Explanation:

- The `disp_Detail()` function opens the binary file "EMP.DAT" for reading in binary mode.

- It reads each record from the file using a while loop.


- Each record is unpacked using `struct.unpack()` to extract the employee ID, name, and salary fields.

- The employee name is decoded from bytes to string and trailing spaces are stripped.

- If the salary is below 25000, the details of the employee (ID, name, and salary) are displayed.

- The process continues until the end of the file is reached.

- Exception handling is used to catch the FileNotFoundError if "EMP.DAT" is not found.

You might also like