# 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' print(int(binary,2))

Output::

5

## 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) i+=1 print(integer) binary_to_decimal("001") binary_to_decimal("010") binary_to_decimal("011")

Output::

1 2 3

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