Is_Even throws error 'returns true; expected false (input was even number)


#1

number = int(raw_input("Enter a number: "))

def is_even(x):

if number % 2 == 0:
    return True
else:
    return False

is_even(number)

Entered 4 as input.
throws error:
Oops, try again.
is_even(-1) returned True instead of the expected: False


15 is_even
#2

in the method implementation you want to check the value x because will be the argument passed for any callbacks

if x % 2 === 0:

#3

Thanks, much, rydan. That did it.


#4

My solution was a bit more complicated, since I used a predefined 'list' for input

numbers = [1,2,3,4,5,6,7,8,9];

def is_even(number):
    if number % 2 == 0:
        print number, "is even"
        return True
    else:
        print number, "is odd"
        return False

for number in numbers:
    is_even(number)

#5

you just use x instead of number:

x = int(raw_input("Enter a number: "))
def is_even(x):
if x % 2 == 0:
return True
else:
return False


#6

Why is this requesting an arithmetic result of '0'?: ' if x % 2 ==0: '
Pardon my ignorance, I just don't get why a number that is divisible by 2 is considered to "equal" zero...

Appreciate the attention if anyone is able to respond!


#7

Using the "% 2" is not inspecting the answer after dividing the number by 2, it is requesting the remainder of the number when divided by 2. The arithmetic result of "3 / 2 = 1 with a remainder(R) of 1" while "4 / 2 = 2 R0" there by identifying it is even. All even numbers will result in a remainder of "0" if divided by 2 while all odd numbers will have a remainder of "1" when divided by 2.


#8

I don't get why you have to do x % 2 == 0?


#9

Because you are asking for the remainder of the equation "x / 2" to be equal (==) to zero. Think of what makes an integer odd or even, if a number can be divided evenly by 2 with no remainder it is even, if there is a remainder of 1 it is odd.
examples:
10 % 3 = 1 (3 goes into 10 "3" times with "1" left over)
11 % 3 = 2 (3 goes into 11 "3" times with "2" left over)
12 % 3 = 0 (3 goes into 12 "4" times with "0" left over)
I hope this helps.