AppDividend
Latest Code Tutorials

Python oct() Function Example

0

If you want to convert an integer to octal number, then the Python oct() method is convenient. Python oct() method returns an octal representation of a given number. The oct() method takes the integer number and returns its octal representation. If a given number is an int, it must implement the __index__() method to return the integer.

Python oct()

Octal strings in Python are prefixed with 0o.

The syntax of the Python oct() method is the following.

oct(x)

This function has only one parameter that is the integer type number, and it can be in binary or hexadecimal or decimal form.

If the value of x is other than an integer type, then the program will return a TypeError.

The oct() method returns an octal string from the given integer number.

How oct() works in Python

See the following code example.

# app.py

# When input is a decimal number
print("Octal representation is: ", oct(130))

# When input is in binary format
print("Octal representation is: ", oct(0b1111))

# When an input is in hexadecimal format

print("Octal representation is: ", oct(0XAC))

Output

➜  pyt python3 app.py
Octal representation is:  0o202
Octal representation is:  0o17
Octal representation is:  0o254
➜  pyt

On the above program, we can see that we have converted the decimal, binary, and hexadecimal type of input into an octal format.

Each time, we got one string starting with 0o, which indicates that the number is in octal format. Like, we have 0b for binary number and 0x / 0X for hexadecimal number.

When given input is not an integer

See the following code.

# app.py

class Octal:
    x = 115

    def __init__(self):
        return self.x


octal = Octal()
print("The octal value is: ", oct(octal))

Output

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 8, in <module>
    octal = Octal()
TypeError: __init__() should return None, not 'int'
➜  pyt

Here, in this example, as the given input is not an integer type input, the compiler gives us a run time error (TypeError).

Python oct() with custom objects

See the following code.

# app.py

class Student:
    age = 18

    def __index__(self):
        return self.age

    def __int__(self):
        return self.age


stud = Student()
print('The oct is:', oct(stud))

Output

➜  pyt python3 app.py
The oct is: 0o22
➜  pyt

In this example, we will use the oct() function with a custom object as an argument. We will implement __index__() function in this object.

Related Posts

Python static method

Python format()

Python exec()

Python setattr()

Python print()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.