Python 返回菜单时,行仅打印一次
我正在做一个测验,我有一个文本文件,必须从中检索保存的分数和用户名。然而,当我得到分数返回主菜单时,只会显示一个结果 这是我的文本文件的外观:Python 返回菜单时,行仅打印一次,python,Python,我正在做一个测验,我有一个文本文件,必须从中检索保存的分数和用户名。然而,当我得到分数返回主菜单时,只会显示一个结果 这是我的文本文件的外观: 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 这是我的代码: def results(): fo
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
这是我的代码:
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()
由于返回菜单命令(我必须让程序返回主菜单),只显示文本文件中的第一个结果(在本例中为Ted History Easy 4 points Grade:B),但只要我去掉返回菜单()的代码行,就会显示输入的用户名的所有结果。如何让代码显示所有结果并返回主菜单?如果要打印多个结果,只需从循环中删除
return
语句即可,即:
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
您也不需要return menu()
,除非您希望results()
函数返回menu()
返回的内容
您将注意到的代码的另一个问题是,当有人输入
点作为用户名时。您可能希望将您的条件形成为:if line.startswith(username):…
您可以发布完整的代码吗?您的return语句在第一次迭代时结束循环。在编程中,不要缩进它return
,这并不完全意味着“转到其他地方”,而是意味着“将该变量返回给调用函数”