为什么循环不停止使用 'continue'?

Why is loop not stopping using 'continue'?

所以我是编程新手,我正在编写一些练习代码 (Python 3.6):

while True:
    print('Hello Steve, what is the password?')
    password = input()
    if password != '1234':
        continue
    print('Access granted')

我遇到的问题是,即使我输入了正确的密码,循环 continues.Can 你能帮我找出我做错了什么吗?

continue 改为 break,应该可以。

continue 将跳过 循环中剩余的当前回合 ,然后循环将重新开始:

>>> i = 0
>>> while i < 5:
...     i += 1
...     if i == 3:
...         continue
...     print(i)
...
1
2
4
5
>>>

你要找的是 break 关键字,它将完全退出循环:

>>> i = 0
>>> while i < 5:
...     i += 1
...     if i == 3:
...         break
...     print(i)
...
1
2
>>>

但是,请注意 break 将完全跳出循环,而您的 print('Access granted')after。所以你想要的是这样的:

while True:
    print('Hello Steve, what is the password?')
    password = input()
    if password == '1234':
        print('Access granted')
        break

或者使用 while 循环条件,尽管这需要重复 password = ...:

password = input('Hello Steve, what is the password?\n')
while password != '1234':
    password = input('Hello Steve, what is the password?\n')
print('Access granted')

首先,您使用了错误的逻辑运算符进行相等比较,这个:!= 用于 不等于 ;而这个 ==equals.

其次,正如其他人已经指出的那样,您应该使用 break 而不是 continue

我会这样做:

print('Hello Steve!')
while True:
    password = input('Type your password: ')
    if password == '1234':
        print('Access granted')
        break
    else:
        print('Wrong password, try again')

尝试使用 break 语句而不是 continue。 您的代码应如下所示

while True:
    print('Hello Steve, what is the password?')
    password = input()
    if password == '1234':
        print('Access granted')
        break