虽然已经满足条件,但循环仍在继续(使用Python)

时间:2018-01-30 19:59:54

标签: python python-2.7 while-loop

这是我的代码:

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很陌生,所以如果我在浪费任何人的时间,我很抱歉。

3 个答案:

答案 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'