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:
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.if number % 2 == 0:
: This is the core of the divisibility check.number % 2
calculates the remainder whennumber
is divided by 2.== 0
checks if the remainder is equal to 0. If it is, the condition isTrue
, meaning the number is divisible by 2.
print("The number is divisible by 2")
: If the condition in theif
statement isTrue
, this line prints the message "The number is divisible by 2".else:
: If the condition in theif
statement isFalse
(i.e., the remainder is not 0), the code inside theelse
block is executed.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.