counting

In high-low, the user gets 7 guesses to pick the right number. So we need a way to count how many guesses the user has left.

Consider again our password code:

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")

How could we modify this so that the last line tells us how many guesses it took us, like this?

>>> %Run password.py
What's the secret password? guacamole
wrong!
What's the secret password? jacob is so handsome
wrong!
What's the secret password? friend
That is correct. It took you 3 tries.

Think about that for a moment. Ok I’ll tell you:

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

print("That is correct. It took you", tries, "tries.")

Each time the loop runs, we add 1 to the value of tries.

TIP


Instead of `tries = tries + 1`, you can also type `tries += 1`. This works for all the arithmetic operators. For example, `foo *= 3` is the same as `foo = foo * 3` and `bar -= foo` is the same as `bar = bar - foo`.

previous: while loops next: exercises