Your own while/else


#1


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


I got very confused on this exercise,I didn't know why this code didn't work originally I thought for awhile and I tried making guesses_left global and it worked.Though I want to know what the lesson wanted instead of using the global
keyword


Original way:




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


Global way:



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

Thanks in advanced :smiley:


#2

First according to the question guesses_left should be greater than 0,

and you have to write the else statement inside the while loop.


#3

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