Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,175 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