这是我的代码:
while True:
chosenUser = raw_input("Enter a username: ")
with open("userDetails.txt", "r") as userDetailsFile:
for line in userDetailsFile:
if chosenUser in line:
print "\n"
print chosenUser, "has taken previous tests. "
break
else:
print "That username is not registered."
即使在输入用户名并输出结果后,循环仍会继续并要求我再次输入用户名。在
我最近问过一个类似的question,但我自己也做到了。不管我怎么努力,这个都不行。在
有什么办法解决吗?在
注意:userDetailsFile
是程序中先前的文本文件。在
这个问题可能很明显,但我对Python还不熟悉,所以如果我浪费了任何人的时间,我很抱歉。在
正如其他人所指出的,主要问题是}循环中断,这可以使用例如布尔变量或
break
只从内部for
循环中断,而不是从外部{return
来修复。在但是,除非您希望为每个不包含用户名的行打印“not registered”行,否则应该使用^{} 而不是{}。但是,与使用
for
循环不同的是,您还可以将next
与生成器表达式一起使用,以获得正确的行(如果有的话)。在或者,如果您实际上不需要
^{pr2}$lineWithUser
,只需使用any
:这样,代码也更紧凑,更容易阅读/理解它在做什么。在
解决此问题的最简单方法是使用布尔变量并切换它,使外部
while
可更改:这样你就可以从一个内部循环中停止外部循环。在
break
仅中断内部for
循环。 最好将所有内容放入函数中,并使用return
停止while
循环:相关问题 更多 >
编程相关推荐