Practice!practice!practice!


#1

THIS SHOULDN'T WORK :thumbsdown:

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/2?curriculum_id=4f89dab3d788890003000096#

:confused: My answer goes against the instructions but it works :confused:


def is_even(x):
    if x % 2:
        return False
    else:
        return True


Here's a screenshot!


#2

Hi @luftangrieferii,

Your solution is correct, even though it differs from what most users submit for this exercise.

Do you know why it works?


#3

No, Sadly. That's exactly why I came to the forums. :sob:


#4

The if block condition is x % 2. When x is an odd number that condition evaluates to 1. The Python interpreter considers 1 to be equivalent to True when it is used as a condition. Therefore, for odd values of x the if block executes, which contains this line ...

return False

That is the correct result for odd values of x.

When x is an even number the condition evaluates to 0. The Python interpreter considers 0 to be equivalent to False when it is used as a condition. Therefore, for even values of x the else block executes, which contains this line ...

return True

That is the correct result for even values of x.

Therefore, your solution works, and is consistent with the instructions.

Cool :sunglasses:


#5

How does the interpreter know what x is = to


#6

x does not have a value until someone calls the function. An example of a function call would be ...

print is_even(7)

When that statement is executed, the is_even function is called and the value 7 is assigned to x. Then the Python interpreter can execute the function based on that value of x.

In the above case, this is displayed ...

False

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.