Problem #1
def main():
with open("student_grades.txt","w") as file:
for i in range(5):
name = input(f"Enter the name of the student{i+1}: ")
grade = input(f"Enter the grade of {name}: ")
file.write(f"{name} - {grade}\n")
total_grade = 0
student_count = 0
with open("student_grades.txt","r") as file:
print("\nStudent Records:")
for line in file:
print(line.strip())
name, grade = line.strip().split(" - ")
total_grade += float(grade)
student_count += 1
average_grade = total_grade / student_count
print(f"\nAverage grade: {average_grade:.2f}")
with open("student_grades.txt","a") as file:
file.write("------End of Student Grades------\n")
if __name__ == "__main__":
main()
This program collects student names and grades, writes them to a file, reads and displays the
data, calculates the average grade, and appends a closing message. The main() function is the
starting point of the program. First, it opens a file named student_grades.txt in write mode
("w") to store student records. The program prompts the user to enter the names and grades of 5
students using a loop. Each student’s name and grade are written to the file in the format "name
- grade". After collecting the data, the file is closed.
Next, the program opens the same file in read mode ("r") to process the stored records. It reads
each line of the file, prints the student’s name and grade, and splits the line into the name and
grade. The grade is added to a running total, and the student count is incremented. After reading
all records, the program calculates the average grade by dividing the total grade by the student
count.
The average grade is displayed with two decimal places. Finally, the program reopens the file in
append mode ("a") and writes a closing message: "------End of Student Grades------".
The if __name__ == "__main__" block ensures that the main() function runs when the script
is executed directly. This structure allows for proper file handling, ensuring data is written, read,
and processed efficiently.
The program does not currently validate grade input, so entering non-numeric or out-of-range
values would result in an error. It is designed to handle exactly 5 students, but this could be made
more flexible. The average is calculated as a simple arithmetic mean. The program closes the file
automatically after each operation using the with open() statement, which ensures proper
resource management.
This code can be extended with more error handling and input validation to improve robustness
Problem #2
def main():
with open("employee_salaries.txt", "w") as file:
for i in range(5):
name = input(f"Enter the name of employee {i+1}: ")
while True:
try:
salary = float(input(f"Enter the salary of {name}: "))
break
except ValueError:
print("Invalid input. Please enter a numeric value for salary.")
file.write(f"{name} - {salary}\n")
total_payroll = 0
highest_salary = 0
highest_salary_employee = ""
with open("employee_salaries.txt", "r") as file:
print("\nEmployee Records:")
for line in file:
print(line.strip())
name, salary = line.strip().split(" - ")
salary = float(salary)
total_payroll += salary
if salary > highest_salary:
highest_salary = salary
highest_salary_employee = name
print(f"\nTotal Payroll: {total_payroll:.2f}")
print(f"Highest Salary: {highest_salary:.2f} (Employee: {highest_salary_employee})")
# Append the end of record message
with open("employee_salaries.txt", "a") as file:
file.write("---End of Employee Salaries---\n")
if __name__ == "__main__":
main()
Explaination:
Explanation of the Code:
1. Creating the File:
o The program opens a file named employee_salaries.txt in write mode ("w"),
creating the file if it doesn't exist.
2. Collecting Employee Data:
o The program prompts the user to enter the name and salary of 5 employees.
o For each employee, the program ensures the salary is a valid float using a while
loop and try-except block to catch invalid inputs.
3. Saving Employee Data:
o Each employee's name and salary are saved to the file in the format "Name -
Salary", with each record written on a new line.
4. Reading and Displaying Records:
o The program reopens the file in read mode ("r"), reads the records, and displays
them one by one.
o It also calculates the total payroll by summing all salaries and tracks the highest
salary and the corresponding employee.
5. Displaying Results:
o After reading the records, the program prints the total payroll and the highest
salary along with the name of the employee who received it.
6. Appending the End of File Message:
o Finally, the program appends the line "---End of Employee Salaries---" to
the file to mark the end of the employee data.