How to Count the Set Bits in an Integer in Python
In this tutorial, we will learn how to program "How to Count the Set Bits in an Integer in Python." The objective is to count the number of set bits (1s) in the binary representation of a given integer. This tutorial will guide you step by step through the process of determining the set bits for any integer input. By the end of this tutorial, you will have a solid understanding of how to efficiently count set bits in Python, helping you strengthen 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 efficient way to count the set bits in an integer. 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 count_set_bits(n):
- count = 0
- while n:
- n &= n - 1
- count += 1
- return count
- while True:
- print("\n============== Count the Set Bits in an Integer ==============\n")
- number = int(input('Enter a number: '))
- print('Number of set bits:', count_set_bits(number))
- 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 Python program repeatedly prompts the user to input an integer and then calculates the number of set bits (i.e. the number of 1s in its binary representation) using Brian Kernighan’s algorithm. It continues running until the user chooses to exit.
Output:

There you have it we successfully created How to Count the Set Bits in an Integer 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