这是我的代码:
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很陌生,所以如果我在浪费任何人的时间,我很抱歉。
答案 0 :(得分:2)
正如其他人所指出的那样,主要问题是break
仅从内部for
循环中断,而不是从外部while
循环中断开,这可以使用例如布尔变量或return
。
但除非您希望为每个不包含用户名的行打印“未注册”行,否则应使用for/else
代替if/else
。但是,您可以使用带有生成器表达式的for
代替使用next
循环来获取正确的行(如果有的话)。
while True:
chosenUser = raw_input("Enter a username: ")
with open("userDetails.txt", "r") as userDetailsFile:
lineWithUser = next((line for line in userDetailsFile if chosenUser in line), None)
if lineWithUser is not None:
print "\n"
print chosenUser, "has taken previous tests. "
break # will break from while now
else:
print "That username is not registered."
如果您实际上不需要lineWithUser
,请使用any
:
while True:
chosenUser = raw_input("Enter a username: ")
with open("userDetails.txt", "r") as userDetailsFile:
if any(chosenUser in line for line in userDetailsFile):
print "\n"
print chosenUser, "has taken previous tests. "
break # will break from while now
else:
print "That username is not registered."
这样,代码也更紧凑,更容易阅读/理解它正在做什么。
答案 1 :(得分:0)
解决此问题的最简单方法是使用布尔变量使外部while
可变,并将其切换:
loop = True
while loop:
for x in y:
if exit_condition:
loop = False
break
这样你可以从内部循环中停止外循环。
答案 2 :(得分:0)
break
仅突破内部for
循环。
最好将所有内容放入函数中,并使用while
停止return
循环:
def main():
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. "
return # stops the while loop
print "That username is not registered."
main()
print 'keep going here'