Python Program to Convert Octal to Decimal

In this tutorial we are going to write a python program to convert octal number to decimal number.

Recommend read to know how to convert octal number to decimal number (with algorithm): octal to decimal conversion in C.

Python program to convert octal to decimal

Here is the source code of python program to convert octal to decimal using inbuilt functions.
octal = input("Enter any octal number: ")

decimal = int(octal, 8)
  
print("Decimal equivalent of octal","is",decimal)

Output:

Enter any octal number: 053
Decimal equivalent of octal 053 is 43

Explanation:

We have accepted an octal number. int() converts a decimal number to octal if you specify base 8 and pass a decimal number. But if you pass an octal number and specify base 8 you get a decimal equivalent. So we have used inbuilt function int to convert octal to decimal. That's all to this program.

Another way of octal to decimal conversion is by using the native code.

Python program for octal to decimal conversion using while loop

octal = input("Enter any octal number: ")

decimal = 0

base = 1

# store octal number into temporary variable
temp = int(octal)

while (temp): 
        last_digit = temp % 10
        temp = int(temp / 10)
        decimal += last_digit * base
        base = base * 8
        
print("Decimal equivalent of octal",octal,"is",decimal)

Output:

Enter any octal number: 052 Decimal equivalent of octal 052 is 42

Comments