7.While / else


#1



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


can anyone explain how this loop works... i got the right answer but did not understand the code...

import random

print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"

count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"



#2

The instructions were to study this code...

import random

print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '5', you lose!"

count = 0
while count < 3:
    num = random.randint(1, 6)
    print num
    if num == 5:
        print "Sorry, you lose!"
        break
    count += 1
else:
    print "You win!"

These lines set up at most three rolls of the die.

while count < 3:
    num = random.randint(1, 6)

A random integer between 1 and 6 is generated by .randint(). If it happens to be a 5, we lose.


#3

Yaayyyyyy.....
now i understand...
thanks...


#4

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