Python 为什么循环不停止使用';是否继续;?

Python 为什么循环不停止使用';是否继续;?,python,python-3.x,while-loop,continue,Python,Python 3.x,While Loop,Continue,因此,我是编程新手,我正在编写一些实践代码(Python 3.6): 我遇到的问题是,即使我输入了正确的密码,循环仍在继续。你能帮我找出我做错了什么吗?更改中断而不是继续,应该可以工作。继续将跳过循环中当前一轮的其余部分,然后循环将重新开始: >>> i = 0 >>> while i < 5: ... i += 1 ... if i == 3: ... continue ... print(i) ... 1 2

因此,我是编程新手,我正在编写一些实践代码(Python 3.6):


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

更改
中断
而不是
继续
,应该可以工作。

继续
将跳过循环中当前一轮的其余部分,然后循环将重新开始:

>>> i = 0
>>> while i < 5:
...     i += 1
...     if i == 3:
...         continue
...     print(i)
...
1
2
4
5
>>>
但是,请注意,
break
将完全跳出循环,您的
print('Access grated')
将在这之后。所以你想要的是这样的:

while True:
    print('Hello Steve, what is the password?')
    password = input()
    if password == '1234':
        print('Access granted')
        break
print('Hello Steve!')
while True:
    password = input('Type your password: ')
    if password == '1234':
        print('Access granted')
        break
    else:
        print('Wrong password, try again')
或者使用
while
循环的条件,尽管这需要重复
密码=…

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

我会这样做:

while True:
    print('Hello Steve, what is the password?')
    password = input()
    if password == '1234':
        print('Access granted')
        break
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

使用
break
而不是
continue
,或者在此基础上进行扩展,while True循环只能使用break语句退出。您希望发生什么?代码对此不是很清楚。所以,使用continue无法做到这一点?很抱歉,我对这些愚蠢的问题很陌生。使用break,它是为了停止循环而提供的,它与continue相反。请详细回答!最后一个给出了
NameError:name“password”没有定义。现在用户必须输入一些东西,但没有被告知他们必须这样做。@StefanPochmann oh master,告诉我如何在Python中
执行
/
。正如我已经提到的,“尽管这需要重复
密码=…
”。Python中没有完美的
do
/
while
,您要么
while True:
(我已经展示)要么重复输入(我已经展示)。如果您有更好的方法,请随时启发我们;)@MarkusMeskanen只需使用
password=None
进行初始化即可。