Python checking whether a number is even
In Python, we can use the modulo operator % to check whether a number is even. If a number divided by 2 has a remainder of 0, then the number is even.
Example
def
is_even
(
number
)
:
return
number %
2
==
0
Testing
num
=
4
if
is_even
(
num
)
:
(
f
"{num} is even"
)
else
:
(
f
"{num} is not even"
)
Code analysis:
is_evenThe function takes a parameternumber, and returnsnumber % 2 == 0result. Ifnumberdivided by 2 has a remainder of 0, it returnsTrue, indicating the number is even; otherwise it returnsFalse。- In the testing section, we defined a variable
numand assigned it the value 4, then calledis_evenfunction to check whethernumis even, and outputs corresponding information based on the result.
Output result:
4 是偶数
Python3 Examples