Reputation: 27
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?
Upvotes: 2
Views: 523
Reputation: 11
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
Upvotes: 0
Reputation: 21883
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')
Upvotes: 8
Reputation: 118
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')
Upvotes: 0