oct() Function in Python

Python oct() Function

In Python, the oct() function is a built-in function that returns the octal representation of an integer. Octal representation is a base-8 numeral system, and it uses digits from 0 to 7. The octal system is rarely used in modern programming but is still occasionally encountered, especially in legacy code or low-level applications.

The syntax of the oct() function is straightforward:

oct(x)

Here, x is the integer value for which you want to obtain the octal representation. The function returns a string representing the octal value of the given integer.

Let's see some examples:

# Example 1
number1 = 10
octal1 = oct(number1)
print(octal1)  # Output: '0o12'

# Example 2
number2 = 42
octal2 = oct(number2)
print(octal2)  # Output: '0o52'

# Example 3
number3 = 255
octal3 = oct(number3)
print(octal3)  # Output: '0o377'

In the output, you will notice that the octal representation is prefixed with '0o', which indicates that the number is in octal format.

Keep in mind that if you provide a number with a floating-point value, the oct() function will raise a TypeError. Also, negative integers can be converted to octal, but the resulting representation will be prefixed with '0o-'.

As mentioned earlier, octal representation is not commonly used in modern Python programming, and you'll usually find decimal (base-10) or hexadecimal (base-16) representations being used in most applications.