'if x% 2: return True', will True return if the number was divisible by 2?

I don’t understand how it works if not x % 2: return True. Does this not mean that if x is not divisible by two, return True? This is what I see in this code.

I see how it if not x % 2: return Truewill return the opposite, if the number is divisible by 2, return True.

I just don't understand how this part of the syntax works.

def is_even(x):
    if not x % 2:
        return True
    else:
        return False
+4
source share
6 answers

Does this mean that if x is not divisible by two, return True?

No, because when x is not divisible by 2, the result x%2will be a non-zero value, which Python will evaluate as True, so it notwill be False.

python.

+10

modul % . x 2 ( "" ), , x % 2, , 0 (= False), True.

+7

, : x % 2 , "x 2"; modulo y , x y (mod 2), x 2.

:

def is_even(x):
    if not x % 2 == 0:
        # if x is divisible by two, the
        # remainder will be 0
        return True
    else:
        return False

. : modulo, python ( " ", .

+1

X/2 0, true

2 % 2 = 0


!0 = true
0

If the operation X modulo 2 = 0, the function returns true - this means that the number is even.

The modulo 2 operation returns the remainder of dividing by 2.

Example:

5 % 2 = 1, because 5 = 2*2 + 1

7 % 2 = 1because use 7 = 3*2 + 1

6 % 2 = 0, because 6 = 3*2 + 0

0
source

Easier and read, for example,

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

where he explicitly indicates that the expression must be zero for the function to return True.

0
source

Source: https://habr.com/ru/post/1621020/


All Articles