Python oct() Function
The Python oct() function is used to convert an integer value into its octal (base-8) representation.
Unlike the familiar base-10 (decimal) system that ranges from 0 to 9, octal uses only the digits "0 to 7". When you see a number prefixed with "0o" in Python, such as '0o17', it means it is in octal notation.
Syntax
Following is the syntax of python oct() function
oct(x)
Parameters
This function accepts an integer value as its parameter.
Return Value
This function returns a string representing the octal value of the given integer.
Example 1
Following is an example of the Python oct() function. Here, we are converting the integer "219" to its octal representation
integer_number = 219
octal_number = oct(integer_number)
print('The octal value obtained is:', octal_number)
Output
Following is the output of the above code
The octal value obtained is: 0o333
Example 2
Here, we are retrieving the octal representation of a negative integer "-99" using the oct() function
negative_integer_number = -99
octal_number = oct(negative_integer_number)
print('The octal value obtained is:', octal_number)
Output
The output obtained is as follows
The octal value obtained is: -0o143
Example 3
Now, we are using the oct() function to convert a binary and a hexadecimal value to their corresponding octal representation
binary_number = 0b1010
hexadecimal_number = 0xA21
binary_to_octal = oct(binary_number)
hexadecimal_to_octal = oct(hexadecimal_number)
print('The octal value of binary number is:', binary_to_octal)
print('The octal value of hexadecimal number is:', hexadecimal_to_octal)
Output
The result produced is as follows
The octal value of binary number is: 0o12 The octal value of hexadecimal number is: 0o5041
Example 4
In the example below, we are removing the "0o" prefix from the output when converting integer value "789" to its octal representation using the oct() function
integer_number = 789
octal_noprefix = oct(integer_number)[2:]
print('The octal value of the integer without prefix is:', octal_noprefix)
Output
The output of the above code is as follows
The octal value of the integer is: 1425
Example 5
If we pass a non-integer value to the oct() function, it will raise a TypeError.
Here we will demonstrate the TypeError by passing a floating point value "21.08" to the oct() function
# Example to demonstrate TypeError
floating_number = 21.08
octal_number = oct(floating_number)
print('The octal value of the floating number is:', octal_number)
Output
We can see in the output that we get a TypeError because we have passed a floating point value to the oct() function
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
octal_number = oct(floating_number)
TypeError: 'float' object cannot be interpreted as an integer