Decimal To Octal Conversion In Python
Published on August 09 2023
In this tutorial you will see how to convert decimal numbers into octal numbers using logical implementation with string. Also, we will use built in methods and understand each line in detail.
Source code
decimal_number = int(input("Enter any positive integer value:"))
# Method - 1 - using custom logic
def decimal_to_octal(num):
octal_value = ""
while num > 0:
remainder = num % 8
octal_value = octal_value + str(remainder)
# octal_value = str(remainder) + octal_value # without reverse approach
num = num // 8
return octal_value[::-1]
# return octal_value # if without reverse approach used
output = decimal_to_octal(decimal_number)
print('Octal Value:', output)
# Method - 2 - using built-in function - oct()
output = oct(decimal_number)
print('Octal:', output[2:])
# Method - 3 - using built-in function - format()
output = format(decimal_number, 'o')
print('Octal:', output)