while loops

Take a look at this:

real_password = "friend"
user_password = input("What's the secret password? ")
while user_password != real_password:
    print("wrong!")
    user_password = input("What's the secret password? ")

print("that is correct")

while, like if, takes an expression on the first line (user_password != password in this case) and then a block of indented code. If the expression evaluates to True, the block of code will run. Then the computer will check the expression again, repeatedly running the block of code until the expression evaluates to False.

Copy and paste the above code into Thonny to see how it works. It will keep asking you for the password until you type friend.

There’s something new you haven’t seen here before: we assigned a different value to a variable (user_password) after creating it. Usually we don’t need to do this. For example, instead of doing this:

x = 1
x = x * 2
x = x + 3
print(x)
4

You can do this:

x = 1
y = x * 2
z = y + 3
print(z)
4

But in the case of our password program, we need to change the existing variable so that the while loop will end.

Make sure you understand how the code above is working. The following code works exactly the same, but it might be a little easier to understand:

real_password = "friend"
user_password = input("What's the secret password? ")

keep_going = True
if user_password == real_password:
    keep_going = False

while keep_going:
    print("wrong!")
    user_password = input("What's the secret password? ")

    if user_password == real_password:
        keep_going = False

print("that is correct")

previous: exercises next: counting