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 trialQui Le
10,998 PointsSmall Challenge from Teacher's Note
Hi Kenneth,
I think about how to make function even() simpler. If num is even, num % 2 will be 0. So, my solution is to use keyword not to negate the condition of whether num % 2. I return True because of the negation of the condition. I return False at the end of function. I don't need to have else statement.
Is that how I improve the function?
2 Answers
gyorgyandorka
13,811 PointsInverting the conditions is irrelevant, the two are equivalent:
def even1(num):
if num % 2 == 0:
return True
return False
def even2(num):
if num % 2 != 0: # equivalent to if not (num % 2 == 0)
return False
return True
Leaving out the else
branch is a valid optimization (in terms of length, at least), but I suppose Kenneth was thinking about an even more concise way :)
def even(num):
return num % 2 == 0
Here's the trick: since num % 2 == 0
is an equality check and thus a boolean expression (an expression which evaluates to True
or False
), we can simply return this expression. If the program encounters an expression like this, it first computes the value of it, then do whatever else it should do with it, in this case return (I see return <something>
on the next line -> let's figure out what that something is -> that something's value is True
-> so I should return True
).
Qui Le
10,998 PointsWow! Your response to the challenge is very concise. It is indeed simple and beautiful. Thank you for your insight!