How to Check Whether a Number is a Power of Two in Python
In this tutorial, we’ll learn how to program "How to Check Whether a Number is a Power of Two in Python." The objective is to accurately check if a given number is a power of two. This tutorial will guide you through the process step by step, helping you understand how to determine whether a number can be expressed as 2 raised to a certain power. By the end, you’ll have a clear understanding of how to efficiently perform this check in Python.
This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the correct and efficient way to check whether a number is a power of two. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def is_power_of_two(n):
- if n <= 0:
- return False
- else:
- return n & (n - 1) == 0
- while True:
- print("\n============= Check Whether a Number is a Power of Two =============\n")
- n = int(input('Enter a number: '))
- if is_power_of_two(n):
- print('{} is a power of two.'.format(n))
- else:
- print('{} is not a power of two.'.format(n))
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program checks whether a given number is a power of two. It uses a bitwise trick: a number n is a power of two if n > 0 and n & (n - 1) == 0. The program runs in a loop, prompting the user for a number, checking the condition, and printing the result. It continues until the user chooses to exit.
Output:

There you have it we successfully created How to Check Whether a Number is a Power of Two in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language