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 trialJason Gabianelli
1,002 PointsWhile loop and even or odd
I am having trouble figuring out what is wrong with my code. I think it has something to do with my if statement but I'm not sure.
import random
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
start = 5
while start != 0:
numb = random.randint(1, 99)
if numb == even_odd:
print("{} is even").format(numb)
else:
print("{} is odd").format(numb)
start = start - 1
1 Answer
Jennifer Nordell
Treehouse TeacherHi Jason! You're doing great, but there are a few problems here. First, you're comparing numb
to even_odd
. But even_odd
is a function that takes one argument and you're not passing in anything. Also, the value returned by the function is not a number but rather a boolean value. It will return true if the number is even and false if it is odd.
Secondly, there is a syntax error in your print
statements and the closed parenthesis you have in the middle should be moved to the end.
Take a look:
start = 5 #set start to 5
while start != 0: #while start is not equal to 0
numb = random.randint(1, 99) #get a random number between 1 and 99
if even_odd(numb): #send the number into the function and check if it's even
print("{} is even".format(numb)) #print the number is even
else: #if the number is odd
print("{} is odd".format(numb)) #print the number is odd
start = start - 1 #decrement start
Hope this clarifies things!
Jason Gabianelli
1,002 PointsJason Gabianelli
1,002 PointsThank you very much! I've been stuck the past day and this really helped