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

Python Python Basics (2015) Letter Game App Even or Odd Loop

Joey B
Joey B
5,275 Points

Why doesn't checking if start is True work for my while loop?

I originally wrote something like this:

import random

start = 5

def even_odd(num):
    # If % 2 is 0, the number is even.
    # Since 0 is falsey, we have to invert it with not.
    return not num % 2

while start == True:
    num = random.randint(1, 99)
    if even_odd(num) == True:
        print("{} is even".format(num))
    else:
        print("{} is odd".format(num))
    start -= 1

Then eventually got it working with

while start > 0:

I'd like to ask why comparing start to True didn't work. I thought that when start would decrement to zero, it would terminate the loop.

if I remember correctly True in binary equates to 1 and False equates to 0. That might be why it works like that.

1 Answer

Steven Parker
Steven Parker
231,248 Points

Regardless of how it may by represented, True is a Boolean, a different kind of thing than a numeric value. Normally, you want to avoid comparing things of different types without some kind of conversion.

So, to do a proper value comparison you could do this:

while start > 0:

But Python has this concept known as "truthiness" (or "falsiness"), which means you can test numeric values for non-zero directly. So you can replace that line with this:

while start:

This is the same way you would test if start actuallly was a Boolean. You never need to compare a Boolean against "True".

Happy coding!   -sp:sparkles:

Joey B
Joey B
5,275 Points

My bad, I had a typo on my post. The code I got it working with was:

while start > 0:

I've corrected my original post.

Thanks so much for the answer! When I run my original code (while start == True:) in workspaces, nothing happens -- no errors or anything. Is it just because I'm trying to compare two different types?

I'm also still trying to wrap my head around "truthiness". Does that mean that a simple while x: or if x: loop by default, checks if that variable is truthy? By the end, my code looked something like this:

while start:
    num = random.randint(1, 99)
    if even_odd(num):
        print("{} is even".format(num))
    else:
        print("{} is odd".format(num))
    start -= 1