Python Check if a Number is Even

Document 对象参考手册Python3 Examples

In Python, we can use the modulo operator%to determine whether a number is even. If the remainder of a number divided by 2 is 0, then the number is even.

Example

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

# Test
num = 4
if is_even(num):
    print(f"{num} is even")
else:
    print(f"{num} is not even")

Code explanation:

  • is_evenThe function accepts one parameternumber, and returnsnumber % 2 == 0the result. Ifnumberthe remainder when divided by 2 is 0, it returnsTrue, indicating the number is even; otherwise it returnsFalse。
  • In the test section, we define a variablenumand assign it 4, then callis_eventhe function to check whethernumit is even, and output the corresponding message based on the result.

Output:

4 是偶数

Document 对象参考手册Python3 Examples

Other extensions