为什么循环不使用"继续"停止?



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

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

我遇到的问题是,即使我输入了正确的密码,循环仍在继续。您可以帮助我找出我做错了什么?

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')是之后的。所以你想要的就是这样:

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')

更改break而不是continue,应起作用。

首先,您要使用错误的逻辑运算符进行平等比较,以下: != for 不是等于;此 ==用于 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语句而不是继续。您的代码应该看起来像这样

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

最新更新