Question


#1

How does e.g "guesses_left -= 1" remove one "guesses_left" on each guess if it has only been written once.

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Pick a number 1 to 10: "))
    print guesses_left
    if guess == random_number:
        print 'You win!'
        break
    guesses_left -= 1
    print guesses_left

else:
    print 'You lose.'

#2

The while loop only works while guesses_left is greater than three, determined by the condition:

Everything inside of this while statement will take place if guesses_left is less than three. The way it continues to decrease and stop itself is that you use

to decrease guesses_left by one. really, it's saying that guesses_left is equal to guesses_left minus one. Every time the while loop occurs, this decrease takes place. I hope this helped! :slight_smile:


#3

uhm... this:

guesses_left -= 1

is a short hand for:

guesses_left = guesses_left - 1

so in every run of the loop, the number stored in guesses_left is reduced by one


#4

Thanks for the help, I understand now :smile:


#5

Thanks again! :smile:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.