Open In App

Python oct() Function

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python.

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.

How oct() Function in Python works?

In this example, we are using oct() to convert an integer to octal in Python. Like we have returned the octal representation of 10 here.

Python3




print(oct(10))


Output

0o12

Example 1: Converting Binary and Hexadecimal Value Into Octal Value

In this example, we are 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: Converting Binary and Hexadecimal Value Into Octal Value Without “Oo” Prefix

To convert a binary or hexadecimal value to an octal representation using Python and remove the “0o” prefix, you can use the oct() function along with string slicing.

Python3




a=10
result=oct(10)[2:]
print(result)


Output

12

Example 4: Demonstrate TypeError in oct() method

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.

Python3




# Python3 program demonstrating TypeError
 
print("The Octal representation of 29.5 is " + oct(29.5))


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. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads