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 detailed step-by-step tutorial on how to check if a number is even or odd in Python:

Step 1: Start by defining a function that takes a number as input. Let's call this function check_even_odd.

Step 2: Inside the function, use the modulo operator % to check if the number is divisible by 2. If the modulo operation returns 0, it means the number is even. Otherwise, it is odd.

Step 3: Return a boolean value True if the number is even, and False if it is odd.

Step 4: Now, let's write the code for the function:

def check_even_odd(num):
if num % 2 == 0:
return True
else:
return False

Step 5: To test the function, you can call it with different numbers and print the result. For example:

print(check_even_odd(4))  # Output: True (4 is even)
print(check_even_odd(7)) # Output: False (7 is odd)

In this example, the check_even_odd function is called with the numbers 4 and 7. The function checks if each number is even or odd and returns the corresponding boolean value. The results are then printed using the print function.

You can also use the function in conditional statements or assign the result to a variable, like this:

num = 12
is_even = check_even_odd(num)
if is_even:
print(f"{num} is even.")
else:
print(f"{num} is odd.")

This code assigns the number 12 to the variable num, calls the check_even_odd function to determine if it is even or odd, and prints the appropriate message based on the result.

That's it! You now have a step-by-step tutorial on how to check if a number is even or odd in Python.