Python oct() Function (original) (raw)
Last Updated : 30 Nov, 2023
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
**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
print
(
oct
(
0b110
))
print
(
oct
(
0XB
))
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))
**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)
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
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.