Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
john larson
16,594 PointsWhy does this never evaluate to False
import random
def result_a():
return random.randint(1, 10)
def result_b():
return random.randint(1, 10)
count = 0
# why does this never evaluate to false
#even when a == b
not_same = True
while not_same:
count += 1
a = (result_a())
b = (result_b())
print(a)
print(b)
print("{} times through the loop".format(count))
if a == b:
not_same == False
Jennifer Nordell
Treehouse TeacherThat's how while loops work. The same is true for JavaScript The part of the while that is the condition must evaluate to be "truthy" for it to be run. For example:
while x < 5. That must evaluate to true to be run. So you're setting "same" to be equal to False. Which is a falsey value. Now you're saying while same. That evaluates to false, so it never runs.
However if you were to do this:
same = False
while !same
This would invert the truthiness of the False causing the evaluation to be true and the loop will execute. Then later on in your code you set same equals to True. So when it gets back up to the top it will invert the "truthiness" which will cause the evaluation to be "falsey" and the while loop will exit
Alternatively, you could go back to your original "not_same" design and just fix the assignment operator
1 Answer
Hannu Shemeikka
16,799 PointsHi,
You are not setting not_same variable to False. You are comparing it against value False.
You should be doing something like
if a == b:
not_same = False # Only 1 '=' for assignment
john larson
16,594 PointsOh yea, silly me. That worked. Thanks. So why does this one one work?
- I changed the while to run as long as it's False
-
but it doesn't run at all
same = False while same: count += 1 a = (result_a()) b = (result_b()) print(a) print(b) print("{} times through the loop".format(count)) if a == b: same = True
Jennifer Nordell
Treehouse Teacherjohn larson you're starting same with False. The while loop will only run while the condition in the while evalutes to True. So it never runs. However, if you were to change the beginning of your while loop to while !same, it should run at least once
john larson
16,594 Pointsjohn larson
16,594 PointsThanks Jennifer, so then while will not run with any False condition, even if I tell it that's the condition to run in.