While循环即使满足条件也会继续(使用Python)

2024-10-02 10:25:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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还不熟悉,所以如果我浪费了任何人的时间,我很抱歉。在


Tags: 代码intrueinputrawwithlineusername
3条回答

正如其他人所指出的,主要问题是break只从内部for循环中断,而不是从外部{}循环中断,这可以使用例如布尔变量或return来修复。在

但是,除非您希望为每个不包含用户名的行打印“not registered”行,否则应该使用^{}而不是{}。但是,与使用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

^{pr2}$

这样,代码也更紧凑,更容易阅读/理解它在做什么。在

解决此问题的最简单方法是使用布尔变量并切换它,使外部while可更改:

loop = True
while loop:
    for x in y:
        if exit_condition:
            loop = False
            break

这样你就可以从一个内部循环中停止外部循环。在

break仅中断内部for循环。 最好将所有内容放入函数中,并使用return停止while循环:

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'

相关问题 更多 >

    热门问题