How to convert binary to decimal in Python

In this tutorial, we will learn how to convert binary numbers to decimal in Python.
Here we will discuss 2 ways in which we can do it.

  • Using in-built function
  • Using for loop

Using in-built function – Convert Binary to Decimal

Python uses inbuilt function int() which converts a number or string to an integer. It returns 0 when the function receives no argument. If x is a number then it returns x. If x is not a number or if the base is given, then x must be a string, bytes, or byte-array instance which represent an integer literal in the given base.

Now let’s look into the code

binary = '101'



Using For Loop – Binary to decimal

Here, using loops we iterate through the binary number which means through each digit which further yields into a decimal number, and now let’s see its execution.

def binary_to_decimal(binary):
    i,integer = 0,0
    size = len(binary)
    while i < len(binary):
        integer += int(binary[size - 1 - i])*pow(2,i)



Here we have created a function binary_to_decimal(binary) which takes the binary number as an argument and then convert the number to its equivalent decimal number.

You can see the output for some sample input of binary numbers.

Hope this tutorial helps you to understand how to convert binary to decimal in Python.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *