Reputation: 67
I'm making a quiz in which I have a text file from which saved scores and usernames have to be retrieved. However, as soon as I get the scores to return to the main menu only one of the results displays.
This is what my text file looks like:
Ted History Easy 4 points Grade : B
Ted Biology Hard 5 points Grade : A
John History Medium 3 points Grade : C
Ted History Medium 2 points Grade : D
This is my code :
def results():
found = False
username = input("Enter username :")
for line in open("scorefile.txt","r"):
if username in line:
print (line)
found = True
return menu()
if not found:
print("No such user")
return menu()
Because of the return menu command (I have to get the program to return to the main menu), only the very first result in the text file is displayed (in this case that being Ted History Easy 4 points Grade : B), but as soon as I get rid of the lines of code saying return menu(), all the results for the username that was input are displayed. How can I get the code to both display all the results and to return to the main menu ?
Upvotes: 1
Views: 36
Reputation: 25799
Just remove your return
statement from the loop if you want to print more than one result, i.e.:
def results():
found = False
username = input("Enter username :")
with open("scorefile.txt","r") as f:
for line in f:
if username in line:
print (line)
found = True
if not found:
print("No such user")
menu() # call your menu() function in the end
You also don't need to return menu()
unless you expect whatever menu()
returns to be returned by your results()
function.
Another problem you will notice with your code is when somebody enters points
as a username. You might want to form your condition as: if line.startswith(username): ...
Upvotes: 2