Power of 2 Checker
Check whether a positive integer is a power of 2 using a loop.
BeginnerTopic: Loop Programs
Python Power of 2 Checker Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to check if a number is a power of 2
n = int(input("Enter a positive integer: "))
if n <= 0:
print("Please enter a positive integer.")
else:
while n % 2 == 0:
n //= 2
if n == 1:
print("It is a power of 2")
else:
print("It is not a power of 2")Output
Enter a positive integer: 16 It is a power of 2
Understanding Power of 2 Checker
We divide by 2 until the number is no longer even; if we eventually get 1, the original number was a power of 2.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.