How to Check if a Number is a Power of Two in Python

In this tutorial, we will learn how to program "How to Check if a Number is a Power of Two in Python." The objective is to determine whether a given number is a power of two. This tutorial will guide you step by step through the implementation, demonstrating how to use logical operations or mathematical approaches to verify the condition. By the end of this tutorial, you will have a clear understanding of how to efficiently perform this check in Python, helping you enhance your problem-solving and coding skills.

This topic is straightforward to understand. Just follow the instructions provided, and you will be able to complete it with ease. The program demonstrated will show you the correct and efficient way to check whether a number is considered 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.
  1. def check_power_of_two(n):
  2.     """Return True if n is a power of two."""
  3.     if n <= 0:
  4.         return False
  5.     else:
  6.         return n & (n - 1) == 0
  7.  
  8. while True:
  9.     print("\n============== Check if a Number is a Power of Two ==============\n")
  10.  
  11.     n = int(input('Enter a number: '))
  12.  
  13.     if check_power_of_two(n):
  14.         print('{} is a power of two.'.format(n))
  15.     else:
  16.         print('{} is not a power of two.'.format(n))
  17.  
  18.     opt = input("\nDo you want to try again?(yes/no): ")
  19.            
  20.     if opt.lower() == 'yes':
  21.         ret=False
  22.     elif opt.lower() == 'no':
  23.         ret=True
  24.         print("Exiting program....")
  25.     else:
  26.         print("Please enter yes/no:")
  27.         break
  28.  
  29.     if ret == False:
  30.         continue

This Python program checks whether a given number is a power of two using bitwise operations. It defines a function check_power_of_two(n) that returns True if the number is a power of two by evaluating the expression n & (n - 1) == 0, which is only true for powers of two. The program repeatedly prompts the user for input and provides the result, continuing based on the user's response.

Output:

There you have it we successfully created How to Check if 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

Python Tutorials