Python’s oct() Function

Python, a versatile programming language, offers a plethora of built-in functions that facilitate various operations. Among these functions is oct(), a powerful tool for converting integers to octal strings.

Understanding oct() Function

The oct() function in Python is primarily used for converting integers to octal notation. Its syntax is straightforward:

oct(x)


Here, x represents the integer that you want to convert to its octal equivalent.

Example 1: Basic Usage

num = 10
octal_num = oct(num)
print("Octal representation of", num, "is:", octal_num)


Output 1:

Octal representation of 10 is: 0o12


Example 2: Using in a Loop

for i in range(5):
print("Octal representation of", i, "is:", oct(i))


Output 2:

Octal representation of 0 is: 0o0
Octal representation of 1 is: 0o1
Octal representation of 2 is: 0o2
Octal representation of 3 is: 0o3
Octal representation of 4 is: 0o4


Example 3: Conversion from String to Octal

num_str = "21"
num_int = int(num_str)
octal_num = oct(num_int)
print("Octal representation of", num_str, "is:", octal_num)


Output 3:

Octal representation of 21 is: 0o25

• The oct() function returns a string representation of the octal value prefixed with ‘0o’.
• It accepts an integer as input and returns its octal equivalent.
• The function is particularly useful in scenarios requiring octal representations, such as low-level programming and permissions manipulation.
Author: user