0

What I believe to have here is a simple syntax error but unfortunately it has stumped my nooby mind. I have googled but had no results, I am looking to return true if the value is even and then false if the value is odd. Thanks!

x = 20

def MyEven(x):

    if x / 2:
        return True
    else:
        return False
    return x
  • Possible duplicate of [python - checking odd/even numbers and changing outputs on number size](http://stackoverflow.com/questions/13636640/python-checking-odd-even-numbers-and-changing-outputs-on-number-size) – Ehsan88 Mar 24 '16 at 02:19

2 Answers2

0

Generally there's no reason to return x unless the situation is more complex than this. If you only want to know if x is even, your code is fine except for two things: return x at the end, and the actual even check. x / 2 will simply return x divided by 2; for x = 20, this will return 10. What you want is x % 10; the % operator returns the remainder of division. If x is even, it returns 0; else, it returns 1.

However- if, for some reason, it is vital to your program that you return x at the end of the function, I would recommend packing your values into a tuple:

x = 20

def MyEven(x):
    result = False # Will remain False if x isn't even
    if x % 2 == 0:
        result =  True
    return (x, result)

This will return a tuple whose first value is the passed x and the second is True or False depending on whether x is even.

MutantOctopus
  • 3,431
  • 4
  • 22
  • 31
0

this should do the trick

def is_even(num):
    return num%2==0

this will return True if num is divisible by 2 (if it is even)

northsideknight
  • 1,519
  • 1
  • 15
  • 24