How to convert a binary number to decimal in Python
How to convert a binary number to decimal in Python.
Here's a step-by-step tutorial on how to convert a binary number to decimal in Python:
First, let's understand the concept of binary and decimal numbers. Binary is a base-2 number system that uses only two digits, 0 and 1. On the other hand, decimal is a base-10 number system that uses digits from 0 to 9.
To convert a binary number to decimal, we need to multiply each digit of the binary number by the corresponding power of 2 and sum them up.
Let's start by taking the binary number as input from the user. You can use the
input()
function to prompt the user to enter a binary number. Here's an example:
binary = input("Enter a binary number: ")
- Next, we'll define a variable
decimal
to store the decimal equivalent of the binary number. Initialize it with 0.
decimal = 0
- Now, we'll iterate through each digit of the binary number from right to left. We can use a
for
loop for this. Here's an example:
for i in range(len(binary)):
# code to be added later
- Inside the loop, we'll check each digit of the binary number. If it is
1
, we'll add the corresponding power of 2 to thedecimal
variable. We can use thepow()
function to calculate the power of 2. Here's the updated code inside the loop:
for i in range(len(binary)):
if binary[i] == '1':
decimal += pow(2, len(binary) - 1 - i)
- Finally, we'll print the decimal equivalent of the binary number. Here's the complete code:
binary = input("Enter a binary number: ")
decimal = 0
for i in range(len(binary)):
if binary[i] == '1':
decimal += pow(2, len(binary) - 1 - i)
print("Decimal equivalent:", decimal)
- Let's test the code with an example. Suppose the user enters the binary number
10101
. The code will calculate the decimal equivalent as21
and print it. Output:
Enter a binary number: 10101
Decimal equivalent: 21
That's it! You've successfully converted a binary number to decimal in Python.