baek82
November 2, 2019, 8:55pm
#1
Hi,
I am trying to use a “while” loop but it’s not working properly - see below.
I want the loop to end if the answer is correct (1111), but it keeps looping incorrectly.
Thank you!
enter_ur_pw = input('Enter your password: ')
correct_pw = 1111
while True:
if enter_ur_pw == correct_pw:
print('Access granted')
break
else:
wrong_pw = input('Oops, try again: ')
1 Like
You need to indent print, break and wrong statements for your if statement to work.
Bruno
November 2, 2019, 11:06pm
#3
The original post actually has indention in its raw form, but since Discourse uses Markdown to parse and render the content, the indentation disappeared.
I’ve now formatted the code as such.
Bruno
November 2, 2019, 11:09pm
#4
Hint.
Run the following code snippet and examine the output.
enter_ur_pw = input('Enter your password: ')
correct_pw = 1111
print(type(enter_ur_pw), type(correct_pw), sep="\n")
3 Likes
baek82
November 3, 2019, 1:42am
#5
You’re a genius @Bruno !! Thanks for this HUGE hint - I finally got it to work
Now that it works…is there a simpler way to write this code (see below) or is this pretty much it? Thanks in advance!!
enter_ur_pw = input('Enter your password: ')
correct_pw = 'abc11'
while True:
if enter_ur_pw == correct_pw:
print('Access granted')
break
else:
wrong_pw = input('Oops, try again: ')
if wrong_pw == correct_pw:
print('Access granted')
break
Bruno
November 3, 2019, 10:59am
#6
Thanks, BK. It’s just experience.
Here’s a shorter version of your code that accomplishes the same thing:
enter_ur_pw = input('Enter your password: ')
correct_pw = 'abc11'
while True:
if enter_ur_pw == correct_pw:
print('Access granted')
break
else:
enter_ur_pw = input('Oops, try again: ')