English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operation

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python oct() usage and example

Python built-in functions

The oct() function takes an integer and returns its octal representation.

The syntax of oct() is:

oct(x)

oct() parameter

The oct() function takes a single parameterx.

The parameter can be:

  • Integer (binary, decimal, or hexadecimal)

  • If it is not an integer, then implement __index__() to return an integer

oct() return value

The oct() function returns an octal string from the given integer.

Example1:How does oct() work in Python?

# Decimal to octal
10) is:10))
# Binary to octal
print('oct(0b101) is:101))
# Hexadecimal to octal
print('oct(0XA) is:', oct(0XA))

Output result

oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12

Example2:Custom object's oct()

class Person:
    age = 23
    def __index__(self):
        return self.age
    def __int__(self):
        return self.age
person = Person()
print('oct:', oct(person))

Output result

oct: 0o27

Here, the Person class implements __index__() and __int__(). That's why we can use oct() on the Person object.

Note:For compatibility, it is recommended to use the same output implementation for int() and index().

Python built-in functions