Your own while/else What is wrong?


#1


Here is the error message
Oops, try again. Make sure to decrement guesses_left


Here is the 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 < 3:
    guess = int(raw_input("your guess: "))
    if guess == random_number:
        print "you win!"
        break
    else:
        print "You lose"


#2

What your causing is an infinite loop which is dangerous. what they mean by decrement is since guesses left is equal to 3

after this block,

you need to write,

guesses_left -= 1

But it must be on the same indentation level as your if statement. :slight_smile:


#3

I have this code now but it is still giving me an error message

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 < 3:
    guess = int(raw_input("your guess: "))
    if guess == random_number:
        print "you win!"
        break
    guesses_left -= 1
    else:
        print "You lose"

It gives me this error message File "python", line 14
else:
^
SyntaxError: invalid syntax


#4

Your else should be on the same indentation level as your while loop so like,


#5

It then shows this error message

Oops, try again. Make sure you store the user guess in a variable called "guess".


#6

Let me see how you've written it now :slight_smile:


#7

while guesses_left < 3:
    guess = int(raw_input("your guess: "))
    if guess == random_number:
        print "you win!"
        break
    guesses_left -= 1
else:
    print "You lose"

#8

Your syntax should look like this,

while guesses_left > 0:
    guess = int(raw_input("Your guess:"))
    if guess == random_number:
        print "You Win!"
        break
    guesses_left -= 1
else:
    print "You Lose."

#9

Thank you! It works now. here is the finished 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 -= 1
else:
    print "You Lose."

#10

You're welcome :relieved:


#11

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