Python oct()

The oct() method takes an integer number and returns its octal representation. If the given number i

The oct() method takes an integer number and returns its octal representation. If the given number is an int, it must implement __index__() method to return an integer.

The syntax of oct() is:

oct(x)

oct() Parameters

The oct() method takes a single parameter x.

This parameter could be:

  • an integer number (binary, decimal or hexadecimal)
  • if not an integer, must implement __index__() method to return an integer

Return value from oct()

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

Example 1: How oct() works in Python?

# decimal number

print('oct(10) is:', oct(10))

# binary number

print('oct(0b101) is:', oct(0b101))

# hexadecimal number

print('oct(0XA) is:', oct(0XA))

When you run the program, the output will be:

oct(10) is: 0o12

oct(0b101) is: 0o5

oct(0XA) is: 0o12

Example 2: How oct() for custom objects by implementing __index__()?

class Person:

    age = 23

    def __index__(self):

        return self.age

    def __int__(self):

        return self.age

person = Person()

print('The oct is:', oct(person))

When you run the program, the output will be:

The oct is: 0o27

Note: For previous compatibility, implement __int__() and __index__() with the same output.

Add comment

CommentList

The file '/Custom/Widgets/ScriptInjection/widget.cshtml' does not exist.