The built-in function oct() is used to get an octal value of a given integer number. This method takes a single argument and returns a converted octal string prefixed with “0o”.
oct(x) #where x must be an integer number and can be binary,decimal or hexadecimal format
Takes a single parameter. This function throws a TypeError if the argument type is other than an integer.
Parameter | Description | Required / Optional |
---|---|---|
integer number | maybe in binary, decimal, or hexadecimal | Required |
If we pass an object as an argument, in such case, the object must have __index__() function implementation to return an integer.
Input | Return Value |
---|---|
integer number | octal string |
# decimal to octal
print('oct(10) is:', oct(10))
# binary to octal
print('oct(0b101) is:', oct(0b101))
# hexadecimal to octal
print('oct(0XA) is:', oct(0XA))
Output:
oct(10) is: 0o12 oct(0b101) is: 0o5 oct(0XA) is: 0o12
class Person:
age = 23
def __index__(self):
return self.age
def __int__(self):
return self.age
pers
print('The oct is:', oct(person))
Output:
The oct is: 0o27
Here, the class Person implements __index__() and __int__(). That's because we can use oct() on the objects of Person.
# Python oct() function example
# Calling function
val = oct(10.25)
# Displaying result
print("Octal value of 10.25:",val)
Output:
TypeError: 'float' object cannot be interpreted as an integer