How to Examine If a Number is Power of 2 in Python


In this example we will show how to check whether a number is a power of 2 in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input('Enter a number: '))
a = n & (n - 1)
if n > 0 and a == 0:
    print('{} is a power of two.'.format(n))
else:
    print('{} is not a power of two.'.format(n))

Output:

Enter a number: 8
8 is a power of two.

Enter a number: 7
7 is not a power of two.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments