Python built-in Method - oct()

htt‮/:sp‬/www.theitroad.com

The oct() function is a built-in Python method that returns the octal (base 8) representation of an integer number. Octal is a number system that uses the digits 0 through 7 to represent numbers.

The syntax for the oct() function is as follows:

oct(x)
  • x: The integer number to be converted to octal representation.

Here's an example usage of the oct() function:

>>> num = 25
>>> oct_num = oct(num)
>>> print(oct_num)
0o31

In the above example, we have an integer number 25. We pass this number as an argument to the oct() function, which returns the octal representation of the number as a string "0o31". The prefix "0o" is added to indicate that the number is in octal format.

We can also use the oct() function with negative numbers:

>>> num = -25
>>> oct_num = oct(num)
>>> print(oct_num)
-0o31

In the above example, we have a negative integer number -25. We pass this number as an argument to the oct() function, which returns the octal representation of the number as a string "-0o31". Note that the prefix "0o" is still added to indicate that the number is in octal format, even though the number is negative.

The oct() function can be useful for formatting numbers in a certain way, or for working with octal numbers in certain programming contexts.