M.Sc Python Programming Assignment 12

M.Sc Python Programming Assignments

Assignment 12

Question:

Given a .txt file that has a list of a bunch of names, count how many of each name there are in the file, and print out the results to the screen.

Code:

				
					def count_names(file_name):
    name_counts = {}

    with open(file_name, 'r') as file:
        for line in file:
            name = line.strip()

            if name in name_counts:
                name_counts[name] += 1
            else:
                name_counts[name] = 1

    return name_counts

file_name = input("Enter the file name: ")

name_counts = count_names(file_name)

print("Name counts:")
for name, count in name_counts.items():
    print(f"{name}: {count}")

				
			

Output:

				
					Name counts:
lucifer: 1

				
			
Tech Amplifier Final Logo