To determine whether a number is odd or even in Python, you can use the modulus operator (%
). The modulus operator returns the remainder when one number is divided by another.
For example, to check if a number is even, you can use the following code:
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(2)) # Output: True
print(is_even(3)) # Output: False
Similarly, to check if a number is odd, you can use the following code:
def is_odd(number):
if number % 2 != 0:
return True
else:
return False
print(is_odd(2)) # Output: False
print(is_odd(3)) # Output: True
You can also use a ternary operator to write this code more concisely:
def is_even(number):
return True if number % 2 == 0 else False
def is_odd(number):
return True if number % 2 != 0 else False
Thok David
February 23, 2023I’m really thankful for joining this website