Sunday, September 22, 2024
Google search engine
HomeLanguagesPython oct() Function

Python oct() Function

Python oct() function takes an integer and returns the octal representation in a string format.

Python oct() Function Syntax

Syntax : oct(x)

Parameters :

  • x – Must be an integer number and can be in either binary, decimal or hexadecimal format.

Returns : octal representation of the value.

Errors and Exceptions : 

  • TypeError : Raises TypeError when anything other than integer type constants are passed as parameters.

Python oct() Function Example

Python3




print(oct(10))


Output:

0o12

Example 1: Base conversion from decimal and binary using oct() function

Using oct() to convert numbers from different bases to octal.

Python3




# Binary to Octal
print(oct(0b110))
  
# Hexa to octal
print(oct(0XB))


Output : 

0o6
0o13

Example 2: Python oct() for custom objects

Implementing __int__() magic method to support octal conversion in Math class.

Python3




class Math:
    num = 76
    def __index__(self):
        return self.num
    def __int__(self):
        return self.num
obj = Math()
print(oct(obj))


Output:

0o114

Example 3 : Demonstrate TypeError in oct() method

Python3




# Python3 program demonstrating TypeError
  
print("The Octal representation of 29.5 is " + oct(29.5))
  
'''
# Python doesn't have anything like float.oct()
# to directly convert a floating type constant
# to its octal representation. Conversion of a
# floating-point value to it's octal is done manually.
'''


Output : 

Traceback (most recent call last):
  File "/home/5bf02b72de26687389763e9133669972.py", line 3, in 
    print("The Octal representation of 29.5 is "+oct(29.5))
TypeError: 'float' object cannot be interpreted as an integer

Applications:  Python oct() is used in all types of standard conversion. For example, Conversion from decimal to octal, binary to octal, hexadecimal to octal forms respectively. 

RELATED ARTICLES

Most Popular

Recent Comments