What is the oct() method in Python?

The oct method is used to convert an integer value to octal.

Syntax

oct(x)

Parameter

The function takes in one parameter, x.

x can be:

  • An integer, binary, and hexadecimal value.
  • Any object which has an implementation of __index__() with an integer return value.

Return value

This method returns the octal representation of the passed argument.

The returned octal value is prefixed with 0o.

Code

print("Integer 9 to octal: ", oct(9))
print("Binary 0b1111 to octal: ", oct(0b1111))
print("Hexadecimal 0xFF to octal: ", oct(0xFF))
class Test:
val = 10
def __index__(self):
return self.val
def __int__(self):
return self.val
print("The octal value of test object: ", oct(Test()))

Explanation

In the code above:

  • We used the oct method to convert the integer, binary and hexadecimal values to octal values.

  • We created a class Test and implemented __index to return an integer value.

  • When we call the oct method with the Test class object as an argument, we will get the octal value of the integer value returned from the __index__ method.

Free Resources