Table of Contents
The oct() function takes an integer number and returns its octal representation.
The syntax of oct()
is:
oct(x)
1. oct() Parameters
The oct()
function takes a single parameter x.
This parameter could be:
- an integer number (binary, decimal or hexadecimal)
- if not an integer, it should implement
__index__()
to return an integer
2. Return value from oct()
The oct()
function returns an octal string from the given integer number.
3. Example 1: How oct() works in Python?
# 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
4. Example 2: oct() for custom objects
class Person: age = 23 def __index__(self): return self.age def __int__(self): return self.age person = Person() print('The oct is:', oct(person))
Output
The oct is: 0o27
Here, the Person
class implements __index__()
and __int__()
. That’s why we can use oct()
on the objects of Person
.
Note: For compatibility, it’s recommended to implement __int__()
and __index__()
with the same output.
Related posts:
Python any()
Python Program to Find Factorial of Number Using Recursion
Python List reverse()
Python Program to Reverse a Number
Python Set difference()
Python Program to Compute all the Permutation of the String
Python globals()
Python Dictionary get()
Python Program to Check Prime Number
Python String isupper()
Python Program to Copy a File
Python Program to Check if a Number is Positive, Negative or 0
Python Anonymous / Lambda Function
Python List clear()
Python Set issuperset()
Python memoryview()
Python delattr()
Python Program to Get Line Count of a File
Python Generators
Python staticmethod()
Python Program to Get the Last Element of the List
Python Program to Check Armstrong Number
Python String startswith()
Python Program to Capitalize the First Character of a String
Python String rfind()
Python Program to Split a List Into Evenly Sized Chunks
Python sum()
Python slice()
Python Program to Randomly Select an Element From the List
Python Type Conversion and Type Casting
Python String swapcase()
Python String center()