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

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,082 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,082 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,082 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.