While / else: Lesson Code Interpretation

#1

I under stand the first 2 lines in console represent the 2 prints.
But I have trouble interpreting the while loop in console.
Here's how I see the code

"While count less than 3 (a number randomly choose between 1 ~ 6 )
print that number that is chosen
however, if the chosen number equals to 5
than print "Sorry you lose"
Once the statement "Sorry you lose" is generated, the while loop stops.

So, my question is, the number "4" is not less than 3, why is it showing up in the console?

``````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 requirement for the loop to continue wasn't that all numbers should be less than three, but a particular one. Is your 4 that particular number? If not, then it's probably not being compared to 3?

#3

So the "print num" still applies to 4 even though 4 does not satisfy while loop?

#4

Why would 4 be compared to 3?

You're assuming that the printed numbers are compared to 3. They're not. What makes you say that they are? That something is wrong. What is compared to 3? You said it yourself, and it's written right there in the condition

Just ask yourself what the program is doing. The number that it prints, should that be compared to 3 at any time in the program?

#5

"The number that it prints, should that be compared to 3 at any time in the program?"

I know this is the difference between while and if loop, where if loop means satisfy if statement all the time to do the print.
But I still don't know how to interpret the while loop.

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

#6

while count is less than three, do the following:

There are no subtleties here. You're missing the obvious. You're not printing the count and the count is what is compared to three. So if you're not printing count, then what is printed is not the count. So what is printed is also not compared to three. Read your code, execute it manually, stare at it.

#7

If I have two variables, A and B.
B is 100.
What is A?

You're essentially saying that because you know B, A must be the same.

#8

Ok, I think I got it. But let me double check with you.

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

count = 0, and because 0 is less than 3, run the loop
and 4, 2 ,5 are all printed because these three numbers are between 1 ~ 6
Sorry you lose is printed because 5 was printed first.
Is this correct interpretation?

#9

If you're unsure about what something does, why not print that information to find out?

#10

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