Python oct() Function
The oct() function in Python converts an integer number into its octal string representation, prefixed with 0o.
Octal numbers use base 8 and are often used in file permissions and low-level computing.
Syntax
oct(number)
Parameters:
number– A valid integer (positive or negative)
Returns:
- A string that represents the octal value of the integer, prefixed with
0o
Example 1: Convert a Positive Integer to Octal
print(oct(10))
0o12
Explanation: 10 in decimal = 1×8 + 2 = 12 in octal
Example 2: Convert a Negative Integer
print(oct(-25))
-0o31
Explanation: The sign is preserved, and 25 in decimal = 3×8 + 1 = 31 in octal.
Example 3: Use with Hex or Binary Converted Values
print(oct(int('0xA', 16))) # Hexadecimal to Octal
0o12
Explanation: 0xA (hex) = 10 (decimal) → 0o12 (octal)
Common Use Cases
- Understanding file permission bits in Unix/Linux systems (e.g.,
chmod 755) - Working with low-level binary/octal representations
- Debugging bitwise operations or memory layouts
Important Notes
oct()only accepts integers. Passing a float or string will raise aTypeError.- The result is always a string, starting with
0o.
Interview Tip
Functions like bin(), oct(), and hex() are often used in bit manipulation problems. Know how to use them and convert between bases.
Summary
oct(n)returns the octal string representation of an integern.- The result starts with
0oand is always a string. - Useful in systems programming, permissions, and binary logic.
Practice Problem
Write a Python program that reads a number from the user and prints its binary, octal, and hexadecimal forms.
num = int(input("Enter a number: "))
print("Octal:", oct(num))
print("Binary:", bin(num))
print("Hexadecimal:", hex(num))
Comments
Loading comments...