Power of 2 Checker in Python

Check whether a positive integer is a power of 2 using a loop.

BeginnerLoop ProgramsExample 15 of 25
power-of-2-checker.py
Run in browser
1# Program to check if a number is a power of 2
2
3n = int(input("Enter a positive integer: "))
4
5if n <= 0:
6 print("Please enter a positive integer.")
7else:
8 while n % 2 == 0:
9 n //= 2
10 if n == 1:
11 print("It is a power of 2")
12 else:
13 print("It is not a power of 2")

Output

Enter a positive integer: 16
It is a power of 2

What's going on

We divide by 2 until the number is no longer even; if we eventually get 1, the original number was a power of 2.