Is_even


#1

Hi,

Not that I have encountered any problem with this lesson but I am confused about one particular bit.

In the code below why is it
x%2==0 and not x%2 only?

I didn't understand the reason behind x is divisible by 2 and then the need to put IS EQUAL TO 0 (==0)

Thank you in advance.

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

#2

% is not a /. It is known as a modulo and returns the remainder. If the number is divisible by 2, that means the remainder is 0, correct?

That is why it is x%2 == 0 instead of just x%2. We need to compare it to something for the statement to be either True or False.


#3

you can do without ==0, but then you need to realize that python evaluates 0 as false, and 1 as true


#4

Now, I understand. Thank you.


#5

Thank you. That makes sense.


#6

datfatcat is actually not right, python is capable of validatiing 1 and 0:

if 1:
   print True #will print true
if 0:
   print True
else:
   print False

#7

Ah yes, Python can validate 0 and 1 (0 being False by default and 1 being True). I'll admit that I'm wrong on that part. But in this case, something like this

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

print(is_even(5)) #evaluates to False

will be harder for others to understand. I usually do x%2 == 0 because it's more comprehensible.


#8

yes its harder to understand. But the learner asked about it. If you want to make it really difficult, combine this + ternary operator:

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

#9

Saves lines/bits which is nice. But yeah, that would be more difficult to understand. Interesting, never heard of ternary operator but it can be useful! Thanks.


#10

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