File handling
File handling
Ans:
2. Write a Python program to copy the contents of one file to another file
Ans:
Ans:
Ans:
def count_specific_word(filename,target_word):
with open("C:\\Users\\ajoak\\Downloads\\Data Science\\hello world.txt","r")
as file:
content = file.read()
words = content.split()
word_count = sum(1 for word in words if word.lower() ==
target_word.lower())
return word_count
5. Write a Python program that prompts the user to input a string and converts it
to an integer. Use try-except blocks to handle any exceptions that might occur
Ans:
def string_to_integer():
user_input = input("Enter the string value: ")
try:
converted_int = int(user_input)
print("The converted integer is: ",converted_int)
except ValueError:
print("Input value is not valid")
string_to_integer()
6. Write a Python program that prompts the user to input a list of integers and
raises an exception if any of the integers in the list are negative.
Ans:
class NegativeIntegerError(Exception):
pass
def check_integers(user_input):
integer_list = list(map(int, user_input.split()))
for number in integer_list:
if number < 0:
raise NegativeIntegerError(f"Negative integer found: {number}")
return integer_list
def main():
user_input = input("Please enter a list of integers separated by spaces: ")
try:
integers = check_integers(user_input)
print(f"The list of integers is: {integers}")
except ValueError:
print("Error: Please enter valid integers.")
except NegativeIntegerError as e:
print(f"Error: {e}")
main()
7. Write a Python program that prompts the user to input a list of integers and
computes the average of those integers. Use try-except blocks to handle any
exceptions that might occur.use the finally clause to print a message indicating
that the program has finished running.
Ans:
def compute_average(user_input):
integer_list = list(map(int, user_input.split()))
if not integer_list:
raise ValueError("The list of integers is empty.")
def main():
user_input = input("Please enter a list of integers separated by spaces: ")
try:
average = compute_average(user_input)
print(f"The average of the entered integers is: {average:.2f}")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print("The program has finished running.")
main()
8. Write a Python program that prompts the user to input a filename and writes a
string to that file. Use try-except blocks to handle any exceptions that might
occur and print a welcome message if there is no exception occurred.
Ans:
def main():
filename = input("Please enter the filename (with extension): ")
content = "This is a sample string to be written to the file."
write_to_file(filename, content)
main()
9. Build a program to manage a university's course catalog. You want to define a
base class Course that has the following properties:
course_code: a string representing the course code (e.g., "CS101")
course_name: a string representing the course name (e.g., "Introduction to
Computer Science")
credit_hours: an integer representing the credit hours for the course (e.g., 3)
You also want to define two subclasses CoreCourse and ElectiveCourse, which
inherit from the Course class.
CoreCourse should have an additional property required_for_major which is a
boolean representing whether the course is required for a particular major.
ElectiveCourse should have an additional property elective_type which is a
string representing the type of elective (e.g., "general", "technical", "liberal
arts").
Ans:
class Course:
def __init__(self, course_code, course_name, credit_hours):
self.course_code = course_code
self.course_name = course_name
self.credit_hours = credit_hours
def __str__(self):
return f"{self.course_code}: {self.course_name} ({self.credit_hours} credit
hours)"
class CoreCourse(Course):
def __init__(self, course_code, course_name, credit_hours,
required_for_major):
super().__init__(course_code, course_name, credit_hours)
self.required_for_major = required_for_major
def __str__(self):
core_status = "Required for major" if self.required_for_major else "Not
required for major"
return f"{super().__str__()} - {core_status}"
class ElectiveCourse(Course):
def __init__(self, course_code, course_name, credit_hours, elective_type):
super().__init__(course_code, course_name, credit_hours)
self.elective_type = elective_type
def __str__(self):
return f"{super().__str__()} - Elective Type: {self.elective_type}"
def main():
# Create instances of CoreCourse
core_course1 = CoreCourse("CS101", "Introduction to Computer Science", 3,
True)
core_course2 = CoreCourse("MATH201", "Calculus I", 4, False)
main()
10. Create a Python module named employee that contains a class Employee with
attributes name, salary and methods get_name() and get_salary(). Write a
program to use this module to create an object of the Employee class and
display its name and salary.
Ans:
main()