8. Your own while / else


#1

Task:

Instructions
Use a while loop to let the user keep guessing so long as guesses_left is greater than zero.
Ask the user for their guess, just like the second example above.
If they guess correctly, print 'You win!' and break.
Decrement guesses_left by one.
Use an else: case after your while loop to print You lose..

Hint
This game will have a very similar structure, but instead of losing right before the break, the user should win.

The if should check if guess == random_number. If it does, then it's the winning guess!

My code:

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("Your guess:")
    if guess == random_number:
        print "You win!"
        break
    guesses_left = guesses_left - 1
else:
    print "You lose."

Error:

File "python", line 10
    if guess == random_number:
                             ^
SyntaxError: invalid syntax

#2

Oh my God, just second ")" at line 10.

Right code:

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("Your guess:"))
    if guess == random_number:
        print "You win!"
        break
    guesses_left = guesses_left - 1
else:
    print "You lose."

#3

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