Skip to main content

How to check if a number is even or odd in Python

How to check if a number is even or odd in Python.

Here's a step-by-step tutorial on how to check if a number is even or odd in Python:

  1. First, you need to understand the concept of even and odd numbers. An even number is any integer that is divisible evenly by 2, while an odd number is any integer that is not divisible evenly by 2.

  2. To check if a number is even or odd in Python, you can use the modulus operator (%). The modulus operator returns the remainder when one number is divided by another. If the remainder is 0, the number is even; otherwise, it is odd.

  3. Start by defining a function to check if a number is even or odd. Let's call it "is_even_or_odd". Here's an example of how you can define this function:

def is_even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
  1. In this function, the "if" statement checks if the remainder of dividing the number by 2 is equal to 0. If it is, the function returns the string "Even". Otherwise, it returns the string "Odd".

  2. Now, you can call this function and pass a number as an argument to check if it is even or odd. Here's an example:

print(is_even_or_odd(10))  # Output: Even
print(is_even_or_odd(7)) # Output: Odd
  1. In this example, we call the "is_even_or_odd" function twice with different numbers as arguments. The function returns the corresponding result for each number, which is then printed to the console.

  2. Apart from using a function, you can also directly check if a number is even or odd using a conditional statement. Here's an example:

number = 15

if number % 2 == 0:
print("Even")
else:
print("Odd")
  1. In this example, we assign the number 15 to the variable "number". The conditional statement checks if the remainder of dividing the number by 2 is equal to 0. If it is, it prints "Even". Otherwise, it prints "Odd".

  2. You can modify the value of the "number" variable to check if different numbers are even or odd.

That's it! You now know how to check if a number is even or odd in Python using both a function and a conditional statement. Feel free to experiment with different numbers and use cases.