# Convert Binary to Decimal in Python An Easy tutorial

• Post author:

In this tutorial, we will learn how to convert binary numbers to decimal numbers in Python.

A binary number is a number represented in base 2, with each digit being either a 0 or a 1. A decimal number, on the other hand, is a number represented in base 10, with each digit being a number between 0 and 9.

## Examples of converting Binary to Decimal in Python Using loops

``````
def binaryTodecimal(binary):
decimal = 0

for i, digit in enumerate(binary[::-1]):
if digit == '1':
decimal += 2 ** i
return decimal

# test the function
print(bin_to_dec('1001'))  # prints 9

print(bin_to_dec('1010'))  # prints 10

print(bin_to_dec('11011'))  # prints 27
``````

Output:

``````
9

10

27
``````

You can use this function to convert any binary number to a decimal number in Python. Just pass the binary number as a string to the `binaryTodecimal` function and it will return the corresponding decimal number

This function works by iterating through the digits of the binary number from least significant to most significant (right to left). For each digit that is a `1`, it adds 2 to the power of the digit’s position to the decimal number.

## Approach

1. Define a function called `binaryTodecimal` that takes a binary number as a string and returns the corresponding decimal number.
2. Initialize a variable called `decimal` 0. This will store the decimal equivalent of the binary number.
3. Iterate through each digit in the binary number, from least significant to most significant (right to left).
4. For each digit that is a 1, add 2 to the power of the digit’s position to the `decimal` variable.
5. Return the `decimal` variable as the result of the function.

### Publisher

Publisher @ideasorblogs