While loop not working properly

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.

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.

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

You’re a genius @Bruno!! Thanks for this HUGE hint - I finally got it to work :smile:

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

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