Table of Contents
The oct() function takes an integer number and returns its octal representation.
The syntax of oct() is:
oct(x)
1. oct() Parameters
The oct() function takes a single parameter x.
This parameter could be:
- an integer number (binary, decimal or hexadecimal)
- if not an integer, it should implement
__index__()to return an integer
2. Return value from oct()
The oct() function returns an octal string from the given integer number.
3. Example 1: How oct() works in Python?
# decimal to octal
print('oct(10) is:', oct(10))
# binary to octal
print('oct(0b101) is:', oct(0b101))
# hexadecimal to octal
print('oct(0XA) is:', oct(0XA))
Output
oct(10) is: 0o12 oct(0b101) is: 0o5 oct(0XA) is: 0o12
4. Example 2: oct() for custom objects
class Person:
age = 23
def __index__(self):
return self.age
def __int__(self):
return self.age
person = Person()
print('The oct is:', oct(person))
Output
The oct is: 0o27
Here, the Person class implements __index__() and __int__(). That’s why we can use oct() on the objects of Person.
Note: For compatibility, it’s recommended to implement __int__() and __index__() with the same output.
Related posts:
Python getattr()
Python Data Types
Python String expandtabs()
Python dir()
Python frozenset()
Node.js vs Python for Backend Development
Python Program to Find the Factors of a Number
Python Program to Safely Create a Nested Directory
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Set difference()
Python Program to Check If a String Is a Number (Float)
Python Program to Find the Factorial of a Number
Python String splitlines()
Python String endswith()
Python String maketrans()
Python Program to Check Prime Number
Python Program to Display the multiplication Table
Python Machine Learning Eqution Reference - Sebastian Raschka
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Print Output Without a Newline
Deep Learning with Python - Francois Chollet
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Keywords and Identifiers
Python Iterators
Python String index()
Python Program to Print Hello world!
Python pow()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python List pop()
Python Program to Check if a Key is Already Present in a Dictionary
Python Custom Exceptions
Python help()