PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Convert Decimal Numbers to Octal and vice versa

Python Convert Decimal Numbers to Octal and vice versa

Updated on: April 22, 2025 | Leave a Comment

Working with different number systems is a common task in programming, especially in computer science, digital electronics, and networking. Python makes it easy to convert between Decimal (Base-10) and Octal (Base-8).

In this article, you’ll learn how to:

  • Convert a Decimal number to Octal
  • Convert an Octal number to Decimal
  • Do both using built-in functions and manual methods

Table of contents

  • Decimal and Octal Numbers
  • Convert Decimal to Octal In Python
  • Octal to Decimal Conversion in Python
  • Summary

Decimal and Octal Numbers

Decimal Number (Base-10)

  • The decimal system is the standard number system we use every day.
  • It uses 10 digits: 0 to 9.
  • Each digit’s place value is a power of 10.
  • Example: 347 = ( 3 × 10² ) + ( 4 × 10¹ ) + ( 7 × 10⁰ ) = 300 + 40 + 7

Octal Number (Base-8)

  • The Octal Number System is a base-8 number system.
  • Uses 8 digits only: 0 to 7
  • Each place value is a power of 8
  • Example: 157 (octal) = ( 1 × 8² ) + ( 5 × 8¹ ) + ( 7 × 8⁰ ) = 64 + 40 + 7 = 111 (in decimal)

Convert Decimal to Octal In Python

1. Using Built-in oct() Function

In this approach, we will be using the built-in function oct() that converts a decimal to an octal string.

Syntax: oct(x)

  • x must be an integer.
  • Returns a string starting with '0o', indicating octal.
  • For Example, oct(26) = '0o32'

Use the below syntax if you want to remove the ‘0x’ prefix:

octal = oct(26)[2:] # Output: '32'

Note: [2:] slices a string from index 2 to the end, skipping the first two characters.

Code Example

decimal = 26
octal = oct(decimal)
print(f"Octal value: {octal[2:]}")Code language: Python (python)

Output:

Octal value: 32

2. Using format() Function

The format() function in Python converts an integer decimal to its octal representation as a string, without the '0o' prefix.

Syntax: format(number, 'X')

  • number must be an integer (can be positive or negative).
  • 'X': Format code for octal. ‘o’ for octal.
  • Returns a string of octal representation of the integer.
  • For Example, format(255, 'o') = '377'

Note: No '0o' like with oct().

Code Example

decimal = 255
octal = format(decimal, 'o')
print(f"Octal value: {octal}")

# Output:
# Octal value: 377Code language: Python (python)

3. Using F-String Formatting

An F-string (formatted string literal) lets you embed variables, expressions, or formatting instructions directly into a string using {}.

Just prefix the string with f or F and place variables or expressions inside {}.

For Example,

name = "Alice"
age = 25
f"My name is {name} and I am {age} years old."    # Output: My name is Alice and I am 25 years old.

Numbers can be formatted like this:

f"{3.14159:.2f}" # Output: '3.14' → 2 decimal places
f"{{5:b}}" # Output: '101' → binary of 5

f"{255:x}" # Output: 'ff' → hexadecimal of 255
:x inside the f-string formats the decimal as hexadecimal

f"{65:o}" # Output: '101' → Octal of 65

Code Example

decimal = 65
print(f"Octal value: {decimal:o}")  # Lowercase 'o' for octal

# Output:
# Octal value: 101Code language: Python (python)

4. Using a While Loop

In this approach, we manually convert the decimal number into an octal number using while loop.

Algorithm to convert Decimal to Octal in Python:

  1. If the decimal number n is 0, return "0" as the octal result.
  2. Initialize an empty string octal = "" to store the octal result.
  3. Repeat the following steps while n > 0:
    • Find the remainder when n is divided by 8:
      remainder = n % 8
    • Convert the remainder to a string and prepend it to octal:
      octal = str(remainder) + octal
    • Update n by integer division by 8:
      n = n // 8
  4. After the loop ends, return the string octal.

For Example: Convert Decimal 65 to Octal: n = 65

Step 1: n = 65
remainder: 65 % 8 = 1
→ octal = "1"
n = 65 ÷ 8 = 8

Step 2: n = 8
remainder: 65 % 8 = 0
→ octal = "01"
n = 8 ÷ 8 = 1

Step 3: n = 1
remainder: 1 % 8 = 1
→ octal = "101"
n = 1 ÷ 8 = 0

Step 4: n = 0 : stop
The loop ends when the decimal becomes 0.

The octal representation of 65 is: 101

Code Example

def decimal_to_octal(n):
    if n == 0:
        return "0"
    octal = ""
    while n > 0:
        octal = str(n % 8) + octal
        n = n // 8
    return octal

decimal = 65
print("Octal value:", decimal_to_octal(decimal))

# Output:
# Octal value: 101Code language: Python (python)

Octal to Decimal Conversion in Python

1. Using Built-in int() with Base 8

In this approach, we will be using the built-in function int() which converts a octal string to a decimal integer.

Syntax: int(x, base)

  • x: A string or number (in our case, a octal string, like "101")
  • base: The base of the number system (8 for octal)
  • For Example, int("101", 8) # Output: 65

Code Example

oct = "101"
decimal = int(oct, 8)
print(f"Decimal value of {oct} is {decimal}")

# Output:
# Decimal value of 101 is 65Code language: Python (python)

2. Manual Conversion Using Loop

This approach does not use the built-in function but manually converts the Octal number into a Decimal Number using a for loop in Python.

For example, the octal number "127" means:
= ( 1 × 8² ) + ( 2 × 8¹ ) + ( 7 × 8⁰ )
= ( 1 × 64 ) + ( 2 × 8 ) + ( 7 × 1 )
= 64 + 16 + 7
= 87 (in decimal)

Code Example

# function to convert octal to decimal
def octal_to_decimal(octal_str):
    decimal = 0
    power = 0

    # Start from the rightmost digit
    for digit in reversed(octal_str):
        decimal += int(digit) * (8 ** power)
        power += 1

    return decimal

# Example
octal = "127"
print("Decimal value:", octal_to_decimal(octal))

# Output:
# Decimal value: 87Code language: Python (python)

Explanation

  1. Initialize a variable decimal = 0
    • This will hold the final converted value.
  2. Initialize power = 0
    • This represents the position of the digit (starting from the rightmost digit, which is 8⁰).
  3. Reverse the octal string
    • So we can process from the least significant digit to the most significant one.
  4. Loop through each digit in the reversed octal string:
    • Convert the digit (character) to an integer: int(digit)
    • Multiply it by 8^power (i.e., 8 ** power)
    • Add the result to decimal
    • Increment power by 1
  5. After the loop, return or print the final value of decimal.

Summary

Python provides simple and powerful tools for converting between decimal and octal numbers:

  • Use built-in functions like oct() and int(..., 8) for quick results.
  • Try manual methods to understand how number systems work internally.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com