Let’s see a program to check if a number is either even or odd.
The logic is simple: take a number and divide it by 2, if the remainder is 0, then the number is even, otherwise the number is odd.
To get the remainder of a division we use the modulus operator %
.
The code in Python is as follows.
def check_even(number):
if(number % 2 == 0):
return str(number) + ' is even!'
else:
return str(number) + ' is odd!'
print(check_even(16))
#output: 16 is even!
print(check_even(23))
#output: 23 is odd!
If you want to know more about the if
statement, check out this post Conditionals in Python.