Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
115 views

Answer Assignment of Python

The document describes a menu driven Python program to perform various string and file manipulation tasks using user-defined functions. The menu allows the user to 1) replace all occurrences of 's' with 'S' in a new file, 2) count and display the number of words starting with 'a/A' in a file, 3) count words starting with 'a/A' and ending with 'e/E', and 4) replace all occurrences of 'DELHI' with 'NEWDELHI' in an address file. Functions are defined to implement each task with error handling.

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Answer Assignment of Python

The document describes a menu driven Python program to perform various string and file manipulation tasks using user-defined functions. The menu allows the user to 1) replace all occurrences of 's' with 'S' in a new file, 2) count and display the number of words starting with 'a/A' in a file, 3) count words starting with 'a/A' and ending with 'e/E', and 4) replace all occurrences of 'DELHI' with 'NEWDELHI' in an address file. Functions are defined to implement each task with error handling.

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Q1.

Write a menu driven program to do the following tasks with the help of user-defined
functions
1) Find factorial of a number
2) Check if the number is prime or not
3) Fibonacci series up to n terms

Answer:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

def is_prime(n):
if n <= 1:
return False
elif n == 2:
return True
elif n % 2 == 0:
return False
else:
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True

def fibonacci(n):
fib_series = []
a, b = 0, 1
for _ in range(n):
fib_series.append(a)
a, b = b, a + b
return fib_series

def main_menu():
print("Choose an option:")
print("1. Find factorial of a number")
print("2. Check if a number is prime")
print("3. Generate Fibonacci series")
print("4. Quit")

while True:
main_menu()
choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print(f"The factorial of {num} is {result}")
elif choice == '2':
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
elif choice == '3':
n = int(input("Enter the number of Fibonacci terms to generate: "))
if n <= 0:
print("Please enter a positive integer.")
else:
result = fibonacci(n)
print("Fibonacci series up to", n, "terms:")
print(result)
elif choice == '4':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4).")

output
Q2. Write a menu driven program to do the following tasks with the help of user-defined
functions
1) Calculate Simple Interest with r and t as default parameters
2)Calculate X**N with N as default parameter

Ans:
def calculate_simple_interest(p, r=0.05, t=1):
"""
Calculate Simple Interest.

Args:
p (float): Principal amount.
r (float, optional): Rate of interest (default is 5%).
t (int, optional): Time period in years (default is 1).

Returns:
float: Simple Interest
"""
return (p * r * t)

def calculate_power(x, n=2):


"""
Calculate x raised to the power of n.

Args:
x (float): Base number.
n (int, optional): Exponent (default is 2).

Returns:
float: Result of x**n
"""
return x**n

def main_menu():
print("Choose an option:")
print("1. Calculate Simple Interest")
print("2. Calculate X raised to the power of N")
print("3. Quit")

while True:
main_menu()
choice = input("Enter your choice (1/2/3): ")

if choice == '1':
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (in decimal form, e.g., 0.05 for 5%): "))
time = int(input("Enter the time period in years: "))
simple_interest = calculate_simple_interest(principal, rate, time)
print(f"The Simple Interest is: {simple_interest}")
elif choice == '2':
base = float(input("Enter the base number (X): "))
exponent = int(input("Enter the exponent (N): "))
result = calculate_power(base, exponent)
print(f"{base} raised to the power of {exponent} is: {result}")
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3).")

Output

Q3. Write a menu driven program to do the following tasks with the help of user-defined
functions
1) To find length of a string
2) Check for palindrome
3) Change to uppercase
Reverse the string

Ans:
Q4. Write a function in PYTHON to count and display the number of words starting with
alphabet ‘A’ or ‘a’ present in a text file “LINES.TXT”. Example: If the file “LINES.TXT” contains
the following lines, A boy is playing there. There is a playground.
An aeroplane is in the sky.
Are you getting it?
The function should display the output as 5

Ans:
def count_words_starting_with_a(filename):

try:

with open(filename, 'r') as file:

content = file.read()

words = content.split()

count = 0

for word in words:

if word[0].lower() == 'a':

count += 1

return count

except FileNotFoundError:

return -1 # File not found error

except Exception as e:

print("An error occurred:", e)

return -2 # Other error

filename = "LINES.TXT"

result = count_words_starting_with_a(filename)

if result == -1:

print("File not found:", filename)

elif result == -2:

print("An error occurred while processing the file.")

else:

print("Number of words starting with 'A' or 'a' in", filename, "is:", result)
Q5. Write a menu driven program to do the following tasks with the help of user-defined
functions
1)Write text to a file.
2)Display all data from file
3)Count and display the total alphabets and digits.
4)Count the total no. of times "the" word occurs.
5)Print the strings in reverse order.

Ans:

Code:

def write_text_to_file(filename):

text = input("Enter the text to write to the file: ")

try:

with open(filename, 'w') as file:

file.write(text)

print(f"Text written to {filename} successfully.")

except Exception as e:

print("An error occurred while writing to the file:", e)

def display_data_from_file(filename):

try:

with open(filename, 'r') as file:

data = file.read()

print("Data from the file:")

print(data)
except FileNotFoundError:

print("File not found:", filename)

except Exception as e:

print("An error occurred while reading the file:", e)

def count_alphabets_and_digits(filename):

try:

with open(filename, 'r') as file:

data = file.read()

alphabets = sum(c.isalpha() for c in data)

digits = sum(c.isdigit() for c in data)

print(f"Total Alphabets: {alphabets}")

print(f"Total Digits: {digits}")

except FileNotFoundError:

print("File not found:", filename)

except Exception as e:

print("An error occurred while reading the file:", e)

def count_occurrences_of_word(filename, word):

try:

with open(filename, 'r') as file:

data = file.read()

word_count = data.lower().count(word.lower())

print(f"The word '{word}' occurs {word_count} times in the file.")

except FileNotFoundError:

print("File not found:", filename)

except Exception as e:

print("An error occurred while reading the file:", e)

def print_strings_in_reverse_order(filename):

try:
with open(filename, 'r') as file:

lines = file.readlines()

print("Strings in reverse order:")

for line in reversed(lines):

print(line.strip())

except FileNotFoundError:

print("File not found:", filename)

except Exception as e:

print("An error occurred while reading the file:", e)

def main_menu():

print("Choose an option:")

print("1. Write text to a file")

print("2. Display all data from the file")

print("3. Count and display total alphabets and digits")

print("4. Count the total number of times 'the' word occurs")

print("5. Print the strings in reverse order")

print("6. Quit")

filename = "data.txt"

while True:

main_menu()

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

if choice == '1':

write_text_to_file(filename)

elif choice == '2':

display_data_from_file(filename)

elif choice == '3':

count_alphabets_and_digits(filename)
elif choice == '4':

word = "the"

count_occurrences_of_word(filename, word)

elif choice == '5':

print_strings_in_reverse_order(filename)

elif choice == '6':

print("Goodbye!")

break

else:

print("Invalid choice. Please select a valid option (1/2/3/4/5/6).")

OUTPUT
Q6. Write a menu driven program to do the following tasks with the help of user-defined
functions
1)Replace 's' with 'S' in new file.
2)Count & display no. of words beginning with 'a' OR 'A'.
3)Count the no. of words beginning with 'a' or 'A' and ending with'e' or 'E'.
4)Replace 'DELHI' with 'NEWDELHI' in address.txt.

Ans:

def replace_s_with_S(input_file, output_file):

try:

with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

for line in infile:

updated_line = line.replace('s', 'S')

outfile.write(updated_line)

print(f"'s' replaced with 'S' in {output_file} successfully.")

except FileNotFoundError:

print("Input file not found:", input_file)

except Exception as e:
print("An error occurred:", e)

def count_words_starting_with_a(input_file):

try:

with open(input_file, 'r') as file:

data = file.read()

words = data.split()

count = sum(1 for word in words if word[0].lower() == 'a')

print(f"Number of words starting with 'a' or 'A': {count}")

except FileNotFoundError:

print("Input file not found:", input_file)

except Exception as e:

print("An error occurred while reading the file:", e)

def count_words_starting_with_a_ending_with_e(input_file):

try:

with open(input_file, 'r') as file:

data = file.read()

words = data.split()

count = sum(1 for word in words if word[0].lower() == 'a' and word[-1].lower() == 'e')

print(f"Number of words starting with 'a' or 'A' and ending with 'e' or 'E': {count}")

except FileNotFoundError:

print("Input file not found:", input_file)

except Exception as e:

print("An error occurred while reading the file:", e)

def replace_delhi_with_newdelhi(input_file, output_file):

try:

with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

for line in infile:

updated_line = line.replace('DELHI', 'NEWDELHI')


outfile.write(updated_line)

print(f"'DELHI' replaced with 'NEWDELHI' in {output_file} successfully.")

except FileNotFoundError:

print("Input file not found:", input_file)

except Exception as e:

print("An error occurred:", e)

def main_menu():

print("Choose an option:")

print("1. Replace 's' with 'S' in a new file")

print("2. Count and display the number of words starting with 'a' or 'A'")

print("3. Count the number of words starting with 'a' or 'A' and ending with 'e' or 'E'")

print("4. Replace 'DELHI' with 'NEWDELHI' in a file")

print("5. Quit")

input_filename = "input.txt"

output_filename = "output.txt"

address_filename = "address.txt"

while True:

main_menu()

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

if choice == '1':

replace_s_with_S(input_filename, output_filename)

elif choice == '2':

count_words_starting_with_a(input_filename)

elif choice == '3':

count_words_starting_with_a_ending_with_e(input_filename)

elif choice == '4':

replace_delhi_with_newdelhi(address_filename, output_filename)
elif choice == '5':

print("Goodbye!")

break

else:

print("Invalid choice. Please select a valid option (1/2/3/4/5).")

Output

Q7. Given a binary file “STUDENT.DAT”, containing records of the following type: [S_Admno,
S_Name, Percentage] Where these three values are: S_Admno – Admission Number of
student (string) S_Name – Name of student (string) Percentage – Marks percentage of
student (float) Write a function in PYTHON that would read contents of the file
“STUDENT.DAT” and display the details of those students whose percentage is above 75

Ans:

import struct
def display_students_above_percentage(filename, threshold):

try:

with open(filename, 'rb') as file:

while True:

# Read one record (a tuple of S_Admno, S_Name, and Percentage)

record = struct.unpack("20s20sf", file.read(struct.calcsize("20s20sf")))

# Check if the file has reached the end

if not record[0]:

break

S_Admno, S_Name, Percentage = record

# Display details if Percentage is above the specified threshold

if Percentage > threshold:

print(f"Admission Number: {S_Admno.decode('utf-8').strip()}")

print(f"Name: {S_Name.decode('utf-8').strip()}")

print(f"Percentage: {Percentage}")

print()

except FileNotFoundError:

print(f"File not found: {filename}")

except Exception as e:

print(f"An error occurred: {e}")

# Usage: Display students with a percentage above 75 from STUDENT.DAT

filename = "STUDENT.DAT"

findmarks = 75.0

display_students_above_percentage(filename, findmarks)

Output
Q8. Write a definition for function BUMPER () in PYTHON to read each object of a binary file
GIFTS.DAT, find and display details of those gifts, which have remarks as “ON DISCOUNT”.
Assume that the file GIFTS.DAT is created with the help of lists of following type:
(ID, Gift, Remarks, Price)

Ans:

Q9. Create a csv file using MS-Excel with the following data:
Name, Age, Qualification, Experience
Ananya,32, PG, 8
Then, write a menu driven program to perform the following operations on the file:
(i) Append record(s) to the file
(ii) Display all the data from the file
(iii)Display all the records with Age<30
(iv)Increase the Experience of all the records by 1
(v) Delete a record with given name and age (to be input from the user).

Q10. Write a program to implement a stack for these book- details (book no, book name).
that is now each item node of the stack contains two types of information – a book no and
its name. just implement Push, pop and display operations.
Ans:

class BookStack:

def __init__(self):

self.stack = []

def push(self, book_no, book_name):

self.stack.append((book_no, book_name))
def pop(self):

if not self.is_empty():

return self.stack.pop()

else:

print("Stack is empty. Cannot pop.")

def is_empty(self):

return len(self.stack) == 0

def display(self):

if not self.is_empty():

print("Stack contents:")

for book_no, book_name in reversed(self.stack):

print(f"Book No: {book_no}, Book Name: {book_name}")

else:

print("Stack is empty.")

# Create a BookStack

book_stack = BookStack()

# Push some book details onto the stack

book_stack.push("B001", "Book A")

book_stack.push("B002", "Book B")

book_stack.push("B003", "Book C")

# Display the stack

book_stack.display()

# Pop an item from the stack

popped_book = book_stack.pop()
if popped_book:

print(f"Popped Book: Book No: {popped_book[0]}, Book Name: {popped_book[1]}")

# Display the stack after popping

book_stack.display()

Q11. Each node of a STACK contains the following information:


a) Pincode of a city b) name of the city
Write a program to implement the following operations in the above stack:
a) PUSH () to push a node in to the stack
b) POP () to remove a node from the stack
c) PEEK () to get the topmost node from the stack
DISPLAY () to display all the nodes in the stack

Ans:
stack = []

def push(pincode, city_name):

stack.append((pincode, city_name))

def pop():

if not is_empty():

return stack.pop()

else:

print("Stack is empty. Cannot pop.")


return None

def peek():

if not is_empty():

return stack[-1]

else:

print("Stack is empty. Cannot peek.")

return None

def is_empty():

return len(stack) == 0

def display():

if not is_empty():

print("Stack contents:")

for pincode, city_name in reversed(stack):

print(f"Pincode: {pincode}, City Name: {city_name}")

else:

print("Stack is empty.")

# Push some city details onto the stack

push("110018", "New Delhi")

push("11088", "JK")

push("110045", "UP")

# Display the stack

display()

# Pop an item from the stack

popped_city = pop()

if popped_city:
print(f"Popped City: Pincode: {popped_city[0]}, City Name: {popped_city[1]}")

# Peek at the top item in the stack

peeked_city = peek()

if peeked_city:

print(f"Top City: Pincode: {peeked_city[0]}, City Name: {peeked_city[1]}")

# Display the stack after popping and peeking

display()

12 SQL queries based on table SPORTS Working


with
MYSQL
13 SQL queries based on table TEACHER Working
with
MYSQL
14 SQL queries based on table EMPLOYEE and JOB Working
with
MYSQL
15 SQL queries based on table EMPLOYEE and SALARY Working
with
MYSQL
16 SQL queries based on table PERSONAL and JOB Working
with
MYSQL
17 SQL queries based on table EMPLOYEES and EMPSALARY Working
with
MYSQL
18 Write a function to read the content from the "quotes.txt" and File
transfer the content to the file "duplicate.txt” but while transfer all the Handling
uppercase characters to lowercase characters, lower case character to Text Files
uppercase character and rest of the character as it is
19 Write a function AverageColumn () which accepts csv file as a Working
parameter. It will print sum and average of each row with .csv
file
20 Write a function to read the contents from the file “India.txt”, and File
store the frequency of each word in dictionary and display the Handling
dictionary in the screen Text Files
21 Write a menu driven program using function Push (), Pop () and Working
Display () to implement the stack. The program will store the with stacks
employee details i.e., Employee number, Employee name and Salary.
22 Write a function update_record_rool(n) to read the student number as Interface
parameter and update the record in student table. Python
with
MYSQL
23 Write a Python database connectivity script that will perform the Interface
following operations on an SQL table of your choice: Python
with
1.Create a table. MYSQL
2.Insert a row.
3.Display all records.
4.Search for a record based on the primary key value.
5.Update a record.
6.Deleate a record
24 Write a Python database connectivity script that will perform the Interface
following operations on an SQL table STUDENT: Python
1. Add a record with
2.Display all records. MYSQL
3.Display records in ascending order of names
4.Display records in descending order of percentage
5.Display the no of student in each stream
25 Write a Python database connectivity script that will perform the Interface
following operations on an SQL table Books and Author Python
1.Add a record in table books. with
2.Display all records of table books. MYSQL
3.Display the books where the pin is between 1000 and 1500.
4.Display the names of authors whose names start with the letter 'M.'
5.Search for a specific book by book number

You might also like