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: Even or Odd Loop

Hey im doing the "Even or Odd Loop Quiz" in "Python Basics". I keep receiving errors. Does anyone know what i did wrong? Task:

Make a while loop that runs until start is falsey. Inside the loop, use random.randint(1, 99) to get a random number between 1 and 99. If that random number is even (use even_odd to find out), print "{} is even", putting the random number in the hole. Otherwise, print "{} is odd", again using the random number. Finally, decrement start by 1.

My Code:

import random

start=5

def even_odd(num):

return not num % 2

while start == True:

var=random.randint(1,99)

if even_odd(var)==True:

    print("{} is even".format(var))

else:

    print("{} is odd".format(var))

start-=1

4 Answers

Tristan Masoud - i think it is for converting from int to boolean but that is different than comparing equal to true. so 5==true is false, but if you set start to 5, then had an if statement say - if start: (body) - then that would evaluate to true and the body would execute. if start were 1, then that would equal true - 1 is the return of an integer cast of true - int(true) would return 1. so another way to fix your code would be to cast start as a boolean with bool(start)==True. a bool cast of any non-zero integer returns true, and true==true, so the loop starts executing, start is decremented each time, and when start is 0, bool(0) is false, and the loop exits.

in your while loop you are comparing an integer variable, start, to a boolean. change to an integer, like while start > 4, and the loop will execute.

Thank you! But i thought that the integer 5 would be considered as True? So why cant i do it like that?

ahh i see! Thank you very much for your help! :)