Home > Mobile >  How do I retrieve the rank of the names from a file and then output the stuff into my print statemen
How do I retrieve the rank of the names from a file and then output the stuff into my print statemen

Time:08-09

I need to open up a file that contains the 1000 most common boy names and how many people have their names. The file is sorted from the greatest used names to the least used names. I have to allow the user to input a name and the program should find the name (regardless of user's input letter case - i.e. upper or lower case) in the dictionary and print out the rank and the number of names. If the name isn’t a key in the dictionary, then the program should indicate this. The program continues until "-1" is entered and should say Exiting program. when this happens.

Example if the user enters “noah”:

Enter a name (-1 to exit): noah Noah is ranked 2 in popularity among boys with 18739 namings. Noah is ranked 692 in popularity among girls with 415 namings.

Enter a name (-1 to exit):

My code so far:

dict1 = {}
boy_names = open('boynames.txt')
for line in boy_names:
    key, value = line.split()

    dict1[key] = value
input = input('Enter a name (-1 to exit):')
grammar = input.lower().capitalize()

for i, (val, key) in enumerate(dict1.items()):

I am not sure what to do after this.

CodePudding user response:

You probably want to use a while loop to do this.

dict1 = {}
boy_names = open('boynames.txt')
for line in boy_names:
    key, value = line.split()

    dict1[key.lower().capitalize()] = value

# as for the while loop.
answer = input('Enter a name (-1 to exit):').lower().capitalize()

while answer != "-1":
   rank = list(dict.keys()).index(answer)   1
   print(f"{answer} appears {dict1[answer]} times and is rank {rank}.")
   answer = input('Enter a name (-1 to exit):').lower().capitalize()

print("Exiting program.")
   
  • Related