Skip to main content

Unit 4 · Loop-de-Loop · Lesson 34 of 57

Three Strikes

Three strikes

Remember the login from Or Else? You got one try. Get it wrong, and the program just ended.

Real logins let you try again, but not forever. (Otherwise someone could just guess until they got in. More on that later!)

Let's give the user 3 tries:

tries = 0

while tries < 3:
    password = input("Password: ")
    if password == "AlexSucksAtCyb3r!":
        print("Welcome!")
        break
    print("Wrong!")
    tries += 1

The new word here is break. It means "get out of this loop, right now." Python stops looping immediately, even if the while question is still True.

So:

  • Right password: print Welcome!, then break out. No more tries needed.
  • Wrong password: print Wrong!, add 1 to tries, and go around again.
  • After 3 wrong tries, tries < 3 is False, and the loop ends on its own.

Build the 3 strike login, and add one thing: if they get it wrong all 3 times, print Locked out! at the end.

The password is purple4life.

They typeIt prints
purple4lifeWelcome!
amer123, then purple4lifeWrong!, then Welcome!
three wrong passwordsWrong! three times, then Locked out!

When you run it, type a password and press Enter for each try.

How do you know if they got locked out? If they got in, the break ended the loop early, so tries is still less than 3. If they got all 3 wrong, tries made it all the way to 3. So after the loop, ask: if tries == 3:

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.