Python - Convert Decimal to Octal Example

In this source code example, we will write a code to convert a decimal number to its octal equivalent in Python.

Python - Convert Decimal to Octal Example

import math

# function to Convert a Decimal Number to an Octal Number.
def decimal_to_octal(num: int) -> str:
    octal = 0
    counter = 0
    while num > 0:
        remainder = num % 8
        octal = octal + (remainder * math.floor(math.pow(10, counter)))
        counter += 1
        num = math.floor(num / 8)  # basically /= 8 without remainder if any
        # This formatting removes trailing '.0' from `octal`.
    return f"0o{int(octal)}"


def main() -> None:
    """Print octal equivalents of decimal numbers."""
    print("\n2 in octal is:")
    print(decimal_to_octal(2))  # = 2
    print("\n8 in octal is:")
    print(decimal_to_octal(8))  # = 10
    print("\n65 in octal is:")
    print(decimal_to_octal(65))  # = 101
    print("\n216 in octal is:")
    print(decimal_to_octal(216))  # = 330
    print("\n512 in octal is:")
    print(decimal_to_octal(512))  # = 1000
    print("\n")


if __name__ == "__main__":
    main()

Output:


2 in octal is:
0o2

8 in octal is:
0o10

65 in octal is:
0o101

216 in octal is:
0o330

512 in octal is:
0o1000

Related Conversions


Comments