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

Nelson Chuang
Nelson Chuang
1,221 Points

i don't get it

looks ok to me?

even.py
import random
start=5

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


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

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

I was able to get your code to pass with three changes.

  • moved even_odd definition ahead of use.
  • compare 'start' in while. If start is non-zero it is "truthy"
  • fixed format typos by replacing comma with period.
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:
  rand=random.randint(1,99)
  if even_odd(rand)==True:
    print("{} is even".format(rand))
  else:
    print("{} is odd".format(rand))
  start=start-1

Try defining the function before using it. Also, it just feels wrong to me to compare start to False, compare it to 0 instead

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Hey Miguel, Moving the function def earlier is correct. However, comparing to False or True, or comparing to the "truthiness" of an object is the Pythonic Way.

oh and try

from random import randint

and then you can use randint on its own

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

In Python it is OK to import a module like random then use random.randint. This keeps the current name space clean and prevents collisions between similarly name objects from different modules. It also helps a code reviewer know which package an object came from without having to scroll back to the top of a long file.