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
Joseph Rivera
1,528 PointsHow exactly does this Python function work?
So I'm completing the "Practice Creating and Using Functions in Python" practice and I'm pretty confused. This code should return True if the inputted number is not divisible by two. I input the following code and got the right answer, but I'm not entirely understanding how the code is working:
def is_odd(num):
num = int(num)
return num % 2 != 0
Can someone please explain. Please and thank you!
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsThe magic is in the return statement:
return num % 2 != 0
return (num % 2) != 0 # modulo is evaluated first
# if number is even, this becomes:
return 0 != 0 # comparison is evaluated, value become Boolean
return False # so False is returned if num is even
# if number is odd, this becomes:
return 1 != 0 # comparison is evaluated, value become Boolean
return True # so True is returned if num is odd
Post back if you need more help. Good luck!
Joseph Rivera
1,528 PointsJoseph Rivera
1,528 PointsThank you! The Parenthesis around the modulo made all the difference.