8. Your own while / else


#1

The code that I have created doesn't really work but Codecademy says it works. It won't let you win at all. Please let me know about the problem in my code and how I should fix it.

from random import randint
random_number = randint(1, 10)
print random_number
guesses_left = 3
while guesses_left > 0:
    guess = raw_input('Guess')
    if guess == random_number:
        print 'You have won.'
        break
    else:
        print 'Wrong'
    guesses_left -= 1
else:
    print 'You lose.'

#2

You may wish to define guess as an integer.

guess = int(raw_input('Guess'))

#3

you have create write code just change this line
"you have won" in place of that write "you win!" as given in instruction it work id.........................


#4

@mtf please i have a doubt can you please clarify it why we used else statement outside the while loop.I am not able to understand this thing.


#5

while..else

The else permits a default segment of code that runs only when break is not activated in the loop.

Consider this rather clumsy example:

from random import randint
n = 0
while n < 10:
    n += 1
    if randint(0,10) == 5: break
else:
    print ("I skipped the break")
print ("after the loop")

In the above example, if a 5 is generated, break is activated. The display reads:

after the loop

If n reaches a count of 10, the loop terminates naturally, thus routing through the else. The display reads,

I skipped the break
after the loop

We only ever need to write an else branch if our loop contains a break AND there is some default code to run. It is pointless otherwise. Just write a normal while statement without an else.


#6

Ohh..Thank you so much for this explanation. It was very hepful.Thanks again.