Answer Assignment of Python
Answer Assignment of Python
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)
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:
content = file.read()
words = content.split()
count = 0
if word[0].lower() == 'a':
count += 1
return count
except FileNotFoundError:
except Exception as e:
filename = "LINES.TXT"
result = count_words_starting_with_a(filename)
if result == -1:
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):
try:
file.write(text)
except Exception as e:
def display_data_from_file(filename):
try:
data = file.read()
print(data)
except FileNotFoundError:
except Exception as e:
def count_alphabets_and_digits(filename):
try:
data = file.read()
except FileNotFoundError:
except Exception as e:
try:
data = file.read()
word_count = data.lower().count(word.lower())
except FileNotFoundError:
except Exception as e:
def print_strings_in_reverse_order(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
print(line.strip())
except FileNotFoundError:
except Exception as e:
def main_menu():
print("Choose an option:")
print("6. Quit")
filename = "data.txt"
while True:
main_menu()
if choice == '1':
write_text_to_file(filename)
display_data_from_file(filename)
count_alphabets_and_digits(filename)
elif choice == '4':
word = "the"
count_occurrences_of_word(filename, word)
print_strings_in_reverse_order(filename)
print("Goodbye!")
break
else:
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:
try:
outfile.write(updated_line)
except FileNotFoundError:
except Exception as e:
print("An error occurred:", e)
def count_words_starting_with_a(input_file):
try:
data = file.read()
words = data.split()
except FileNotFoundError:
except Exception as e:
def count_words_starting_with_a_ending_with_e(input_file):
try:
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:
except Exception as e:
try:
except FileNotFoundError:
except Exception as e:
def main_menu():
print("Choose an option:")
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("5. Quit")
input_filename = "input.txt"
output_filename = "output.txt"
address_filename = "address.txt"
while True:
main_menu()
if choice == '1':
replace_s_with_S(input_filename, output_filename)
count_words_starting_with_a(input_filename)
count_words_starting_with_a_ending_with_e(input_filename)
replace_delhi_with_newdelhi(address_filename, output_filename)
elif choice == '5':
print("Goodbye!")
break
else:
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:
while True:
if not record[0]:
break
print(f"Name: {S_Name.decode('utf-8').strip()}")
print(f"Percentage: {Percentage}")
print()
except FileNotFoundError:
except Exception as e:
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 = []
self.stack.append((book_no, book_name))
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
def is_empty(self):
return len(self.stack) == 0
def display(self):
if not self.is_empty():
print("Stack contents:")
else:
print("Stack is empty.")
# Create a BookStack
book_stack = BookStack()
book_stack.display()
popped_book = book_stack.pop()
if popped_book:
book_stack.display()
Ans:
stack = []
stack.append((pincode, city_name))
def pop():
if not is_empty():
return stack.pop()
else:
def peek():
if not is_empty():
return stack[-1]
else:
return None
def is_empty():
return len(stack) == 0
def display():
if not is_empty():
print("Stack contents:")
else:
print("Stack is empty.")
push("11088", "JK")
push("110045", "UP")
display()
popped_city = pop()
if popped_city:
print(f"Popped City: Pincode: {popped_city[0]}, City Name: {popped_city[1]}")
peeked_city = peek()
if peeked_city:
display()