tsubakitsune
tsubakitsune

Reputation: 5

Search a numbered list using user input and print the result

I've got another class-related problem. I'm not looking for an answer, more just a direction to go in.

For this project, I need to search a list with user input and have it print the result. For example, if you were to search the list for the name "Gabriel", it would print "Gabriel is ranked #5 in the list of popular names". The code I have so far only prints "____ is not ranked"

    boyNames = open('boyNames.txt', 'r')
boyNamesList = boyNames.read().split('\n')
boyNames.close()

 
for i, j in enumerate(boyNamesList, 1):
        userName = input('Enter a name: ')
        if j == userName:
            print(userName, 'is ranked #', i , 'in the list of popular names.')
        else:
            print(userName, 'is not ranked.')
           

Upvotes: 0

Views: 57

Answers (2)

Simon Ward-Jones
Simon Ward-Jones

Reputation: 126

The issue in the code above is that you are asking for the input as part of the loop searching the names. In order to fix move the input to before the loop. Also I have changed to only print the rank after searching through the list.

userName = input('Enter a name: ')
rank = None
for i, name in enumerate(boyNamesList, 1):
    if name == userName:
        rank = i
if rank:
    print(userName, 'is ranked #', i , 'in the list of popular names.')
else:
    print(userName, 'is not ranked.')

Upvotes: 0

General Poxter
General Poxter

Reputation: 554

You need to move the input outside of the for loop:

userName = input('Enter a name: ')
for i, j in enumerate(boyNamesList, 1):
    if j == userName:
        print(userName, 'is ranked #', i , 'in the list of popular names.')
        break
else:
    print(userName, 'is not ranked.')

Your original code asks for an input every iteration, and only checks if the name entered matches the name in the current iteration.

Your logic is also incorrect as you can not say that a name "is not ranked" by just checking userName with the name in the current iteration; you need to check the entire list first before concluding that, so you will need to use a for-else loop.

Upvotes: 1

Related Questions