So I am new at programming and I was writing some practice code (Python 3.6):
while True:
print('Hello Steve, what is the password?')
password = input()
if password != '1234':
continue
print('Access granted')
The problem i'm having is that even though I am typing the correct password, the loop continues.Can you help me figure out what I did wrong?
4 Answers 4
continue will skip the rest of the current round in the loop, and then the loop will start over:
>>> i = 0
>>> while i < 5:
... i += 1
... if i == 3:
... continue
... print(i)
...
1
2
4
5
>>>
What you're looking for is the break keyword, which will exit the loop completely:
>>> i = 0
>>> while i < 5:
... i += 1
... if i == 3:
... break
... print(i)
...
1
2
>>>
However, notice that break will jump out of the loop completely, and your print('Access granted') is after that. So what you want is something like this:
while True:
print('Hello Steve, what is the password?')
password = input()
if password == '1234':
print('Access granted')
break
Or use the while loop's condition, although this requires repeating the 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')
6 Comments
NameError: name 'password' is not defined.do/while in Python. Like I already mentioned, "although this requires repeating the password = ...". There's no perfect do/while in Python, you either while True: (which I've shown) or repeat the input (which I've shown). If you have a better method, feel free to enlighten us ;)password = None instead.Change break instead of continue, should work.
First of all you're using the wrong logical operator for equality comparison, this: != is for not equals; and this == is for equals.
Second, as other have already stated, you should use break instead of continue.
I would do something like this:
print('Hello Steve!')
while True:
password = input('Type your password: ')
if password == '1234':
print('Access granted')
break
else:
print('Wrong password, try again')
Comments
Try using break statement instead of continue. Your code should look like this
while True:
print('Hello Steve, what is the password?')
password = input()
if password == '1234':
print('Access granted')
break
Comments
Explore related questions
See similar questions with these tags.
breakinstead ofcontinue