简体   繁体   English

break 不会中断 while 循环。 为什么?

[英]break doesn't break while loop. why?

I'm trying to do a login system from text file.我正在尝试从文本文件做一个登录系统。
When I enter wrong input that isn't in the text it does what I want it to do, which is to output "wrong username and password" and "try again" and ask for username and pass again.当我输入不在文本中的错误输入时,它会执行我想要它执行的操作,即 output“错误的用户名和密码”和“重试”并询问用户名并再次通过。
But when I enter correct details, the loop never breaks.但是当我输入正确的详细信息时,循环永远不会中断。 It keeps asking for user and pass.它不断询问用户并通过。
Here is my code:这是我的代码:

def check():
        users = open('student.txt').read().split('\n')
        for i in range(len(users)): users[i] = users[i].split(',')


        while True:
            username = str(input('Username: '))
            password = str(input('Password: '))

            for user in users:
                uname = user[3]
                pword = user[4]

                if uname == username and pword == password:
                    print('Hello ' + user[0] + '.')
                    print('You are logged in as: ' + user[3] +  '.')
                    break
                
                    

            else:
                print('Wrong username/password.')
                print('Try again!\n\n')
    check()

The break always leaves the immediate loop construct, the "innermost". break总是离开立即循环构造,即“最内层”。
For your code that is the for loop, not the while loop which contains it.对于您的代码,它是for循环,而不是包含它的while循环。

When using a break statement, it will only exit the inner loop it is currently in, which means it will still be looping the outer loop.当使用break语句时,它只会退出当前所在的内循环,这意味着它仍然会循环外循环。 The common approach for this problem would be to refractor your nested loop into a function and use a return statement to exit the code.解决此问题的常用方法是将嵌套循环重构为 function 并使用return语句退出代码。

Another approach would be adding some continue statement to avoid reaching a second break and only reach it when the inner loop is exited.另一种方法是添加一些continue语句以避免到达第二次break ,并且仅在退出内部循环时才到达它。 Something like this:是这样的:

def check():
      users = open('student.txt').read().split('\n')
       for i in range(len(users)):
            users[i] = users[i].split(',')

        while True:
            username = str(input('Username: '))
            password = str(input('Password: '))

            for user in users:
                uname = user[3]
                pword = user[4]

                if uname == username and pword == password:
                    print('Hello ' + user[0] + '.')
                    print('You are logged in as: ' + user[3] + '.')
                    break
            else:
                print('Wrong username/password.')
                print('Try again!\n\n')
                
                # Continue if the inner loop wasn't broken.
                continue

            # Inner loop was broken, break the outer.
            break

the break statement will break out of while AND for loops. break语句将跳出while AND for循环。 As frustrating as it might seem, these break statements will only break out of the closest loop.尽管看起来令人沮丧,但这些 break 语句只会跳出最近的循环。 If you take a look at your code, you can see that your break statement is actually called inside of a for loop within your while loop .如果查看代码,您会发现 break 语句实际上是在while loop内的for loop内调用的。 This means you are breaking out of the for loop but the while loop will continue on as normal.这意味着您正在跳出for loop ,但while loop将照常继续。

One great alternative to deal with this issue is to turn your while loop into a function and replace your break statement with a return statement.处理此问题的一个很好的替代方法是将 while 循环变成 function 并将break语句替换为return语句。 This way your while loop will also stop!这样你的 while 循环也会停止!

As said in my comment, your break statement is within a for loop that's within a while loop.正如我在评论中所说,您的break语句位于while循环内的for循环内。 break statements won't break any outer loops. break语句不会中断任何外部循环。

Here is a possible solution这是一个可能的解决方案

def check():
        users = open('student.txt').read().split('\n')
        for i in range(len(users)): users[i] = users[i].split(',')

        username = str(input('Username: '))
        password = str(input('Password: '))

        for user in users:
            uname = user[3]
            pword = user[4]

             while True:

                if uname == username and pword == password:
                    print('Hello ' + user[0] + '.')
                    print('You are logged in as: ' + user[3] +  '.')
                    break
            
                else:
                    print('Wrong username/password.')
                    print('Try again!\n\n')

check()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM