zaro

How do you write if a number is divisible by 2 in Python?

Published in Python Programming 2 mins read

You can check if a number is divisible by 2 in Python using the modulo operator (%). If the remainder of the number divided by 2 is 0, then the number is divisible by 2.

Here's how you can do it in Python:

number = int(input("Enter a number: "))

if number % 2 == 0:
  print("The number is divisible by 2")
else:
  print("The number is not divisible by 2")

Explanation:

  1. number = int(input("Enter a number: ")): This line prompts the user to enter a number and then converts the input to an integer. This ensures the input is treated as a numerical value.
  2. if number % 2 == 0:: This is the core of the divisibility check.
    • number % 2 calculates the remainder when number is divided by 2.
    • == 0 checks if the remainder is equal to 0. If it is, the condition is True, meaning the number is divisible by 2.
  3. print("The number is divisible by 2"): If the condition in the if statement is True, this line prints the message "The number is divisible by 2".
  4. else:: If the condition in the if statement is False (i.e., the remainder is not 0), the code inside the else block is executed.
  5. print("The number is not divisible by 2"): This line prints the message "The number is not divisible by 2" if the number is not divisible by 2.

Example:

If the user enters the number 10, the output will be:

The number is divisible by 2

If the user enters the number 7, the output will be:

The number is not divisible by 2

This method effectively determines whether a number is even or odd by checking its divisibility by 2.