Python oct() Function
The oct() function in Python is used to convert an integer into its octal string representation.
note
Octal strings in Python are prefixed with 0o.
Syntax
oct(x)
oct() Parameters
Python oct() function parameters:
| Parameter | Condition | Description |
|---|---|---|
x | Required | Must be an integer number. It can be in binary, decimal, or hexadecimal format. If not an integer, it should implement the __index__() method to return an integer. |
oct() Return Value
Python oct() function returns an octal string from the given integer number.
Examples
Example 1: Basic Octal Conversion
Let's convert a decimal number to its octal representation.
integer_number = 219
octal_number = oct(integer_number)
print(octal_number) # Output: 0o333
output
0o333
Other examples:
print(oct(123)) # Output: 0o173
print(oct(456)) # Output: 0o710
print(oct(789)) # Output: 0o1425
print(oct(10000)) # Output: 0o23420
output
0o173
0o710
0o1425
0o23420
Example 2: Octal Conversion of a Negative Integer
integer_number = -219
octal_number = oct(integer_number)
print(octal_number) # Output: -0o333
output
-0o333
Other examples:
print(oct(-123)) # Output: -0o173
print(oct(-456)) # Output: -0o710
print(oct(-789)) # Output: -0o1425
print(oct(-10000)) # Output: -0o23420
output
-0o173
-0o710
-0o1425
-0o23420
Example 3: Converting Binary number to Octal
binary_number = 0b1010
octal_number = oct(binary_number)
print(octal_number)
output
0o12
Other examples:
print(oct(0b111)) # Output: 0o7
print(oct(0b1001)) # Output: 0o11
print(oct(0b1011)) # Output: 0o13
print(oct(0b10000)) # Output: 0o20
output
0o7
0o11
0o13
0o20
Example 4: Converting Hexadecimal number to Octal
hexadecimal_number = 0xA21
octal_number = oct(hexadecimal_number)
print(octal_number)
output
0o5041
Other examples:
print(oct(0xA53)) # Output: 0o5123
print(oct(0xAA11)) # Output: 0o125021
print(oct(0xABCD)) # Output: 0o125715
print(oct(0xA1B2C3)) # Output: 0o50331303
output
0o5123
0o125021
0o125715
0o50331303
Example 5: Handling TypeError for Floating Point Values
The oct() function can not handle floating point values, si it will raise a TypeError exception.
floating_number = 12.3
# This will raise a TypeError because oct() ca nnot handle floating point values.
octal_number = oct(floating_number)
output
Traceback (most recent call last):
File "main.py", line 4, in <module>
octal_number = oct(floating_number)
TypeError: 'float' object cannot be interpreted as an integer
Example 6: Custom Objects with __int__() Method
In this example, a custom class MyClass is defined with an __int__() method to support octal conversion. The oct() function is then used on an instance of this class.
class MyClass:
def __int__(self):
return 10
a = MyClass()
result = oct(int(a)) # 10 in decimal = 12 in octal
print(result) # Output: 0o12
output
0o12