8. Your own while/ else


#1



Hey, I'm having a problem with number 8. If anyone can help, it'd be greatly appreciated! Thanks.

https://www.codecademy.com/courses/python-beginner-en-cxMGf/0/8?curriculum_id=4f89dab3d788890003000096#


The formatting won't work, the syntax is incorrect?
ERROR MESSAGE:

File "python", line 13
else:
^
SyntaxError: invalid syntax


from random import randint

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

guesses_left = 3
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."
# Start your game!


#2

if guess == random_number: #if statement
    print "You win!"
    break
guesses_left -= 1 # End of if.. you close the "if" statement because you forgot the indentation....
else:
    print "You lose."

#3

I fixed that, but I received another error:
File "python", line 12
SyntaxError: 'break' outside loop

from random import randint

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

guesses_left = 3
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."
# Start your game!

#4

I fixed that, but I'm facing another error:

Oops, try again. Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?

from random import randint

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

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

#5

you have to include this line inside your loop because you want to decrements the number of guesses each time you give them chance.

Now you only want to give them another chance at guessing if the answer entered does not match randon_number hence you need to include logic in your loop to handle that like you did here

Below is is little template help you

# import the randint class
from random import randint

random_number = #some random number

guesses_left = #number of gueses

#just to debug
print(random_number)

while guesses_left > 0:

    #note there is no error handling here
    #e.g if the user enters an alphabet, program crashes
    # you can work on that when you get this right
    guess = int(input("Your guess: "))

    if guess matches random_number:
    	#give the user the desired message
        break

    decrement number of guesses_left

else:
    #give the user the game over message

Let me know how it goes


#6

@rydan
Thank you so much! It works!


#7

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