In this tutorial, we are going to discuss how we can convert binary numbers into decimal numbers using a while loop in Python.
In computer programming, binary numbers are used to represent data and instructions.
Binary numbers are composed of only two digits, 0 and 1, which makes it easy to manipulate them using electronic devices.
However, it can be difficult to convert binary numbers to decimal numbers, which are used in everyday life.
In this programming task, we will write a program that uses a while loop to convert a binary number to a decimal.
Simple code:
binary = input("Enter a binary number: ")
decimal = 0
power = 0
while binary:
digit = int(binary[-1])
decimal += digit * 2 ** power
power += 1
binary = binary[:-1]
print("The decimal equivalent is:", decimal)
Output:
Enter a binary number: 010101
The decimal equivalent is: 21
Code With Explanation:
# Take input of binary number
binary = input("Enter a binary number: ")
# Set decimal to 0 initially
decimal = 0
# Set power to 0 initially
power = 0
# Loop until binary is non-empty
while binary:
# Take the last digit of the binary number and convert it to integer
digit = int(binary[-1])
# Add the decimal equivalent of the digit to the total decimal value
decimal += digit * 2 ** power
# Increment the power to move on to the next binary digit
power += 1
# Remove the last digit from the binary number
binary = binary[:-1]
# Print the final decimal equivalent of the binary number
print("The decimal equivalent is:", decimal)
Explanation:
The program takes an input of a binary number and converts it to its decimal equivalent using a while loop.
In the while loop, the last digit of the binary number is taken and converted to an integer.
The decimal equivalent of the digit is then added to the total decimal value.
The power is incremented to move on to the next binary digit, and the last digit is removed from the binary number.
This process continues until all digits have been processed.
Finally, the program prints the decimal equivalent of the binary number.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.