Python Tutorials

Python Programs

Python Convert Decimal to Octal


Python Convert Decimal to Octal

In this tutorial, we will learn how to convert a decimal number to octal in Python. We will cover the basic concept of octal numbers and implement a function to perform the conversion.


What is Octal Conversion

Octal conversion is the process of converting a decimal (base-10) number to an octal (base-8) number. In octal, numbers are represented using digits from 0 to 7.


Syntax

The syntax to convert a decimal number to octal in Python is:

def decimal_to_octal(n):
    return oct(n).replace('0o', '')


Converting a decimal number to octal

We can create a function to convert a given decimal number to octal using Python's built-in functions.

For example,

  1. Define a function named decimal_to_octal that takes one parameter n.
  2. Use the built-in oct function to convert the decimal number to octal.
  3. Remove the '0o' prefix from the octal representation using the replace method.
  4. Return the octal representation as a string.
  5. Call the function with a sample number and print the result.

Python Program

def decimal_to_octal(n):
    return oct(n).replace('0o', '')

# Convert 10 to octal
result = decimal_to_octal(10)

# Print the result
print('Octal representation of 10 is', result)

Output

Octal representation of 10 is 12