8. your own while/else


#1

I have tried and tried. I have used ones from this forum and they fail. This was my last attempt. Anyone out there with something that works
all the time?

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

    elif guesses_left -= 1:
        print 'Guess again.'
    else:
        print "You lose."

#2

Slight change-up:

while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    guesses_left -= 1
    if guess == random_number:
        print "You win!"
        break
    elif guesses_left > 0:
        print 'Guess again.'
else:
    print "You lose."

#3

I at one time had this. I get this;

Oops, try again.
Did you include an else for the while loop?

#4

My typing mistake. Back the else: off to match the while. I'll edit my post above to correct it.


#5

Wow. Thank you. So just getting rid of the indent on else solved it? I thought if, elif, and else were to be indented. wow.


#6

There are two control flow structures in play... while and if. They both have an else clause (optional). In this case, the elif is part of the if statement, and the else is part of the while statement.


#9

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:
"You lose"

but it continues to tell me that i have a syntax error
File "python", line 10
if guess==random_number:
^
SyntaxError: invalid syntax


#10

Guys you are making it more complicated than it needs to be. Just think about it logically.

Here is 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("Guess? : "))
if guess == random_number:
print "You win"
break
guesses_left -= 1
else:
print "You lose"


#11

Thank you, it must had been a misspell error or something but i got it to work.