Python oct Function with Examples

The Python function oct serves the purpose of obtaining the octal representation of a given integer. This function accepts a single argument and outputs the integer as an octal string. If the provided argument is not of the integer type, it raises a TypeError.

Python oct Function Syntax

The syntax of the oct function is given below.

Example

oct (integer)

Parameters

  • integer: A whole number that is intended for conversion into a string formatted in octal representation.
  • Return

It returns an octal string.

Different Examples for Python oct Function

Let’s explore a few examples of the oct function to grasp its capabilities.

Python oct Function Example 1

Here’s a straightforward Python illustration for converting a decimal number into its octal representation.

Example

# Python oct() function example

# Calling function

val = oct(10)

# Displaying result

print("Octal value of 10:",val)

Output:

Output

Octal value of 10: 0o12

Python oct Function Example 2

The oct function exclusively takes an integer as its argument. If a value that is not an integer is provided, an error will occur. Refer to the example shown below.

Example

# Python oct() function example

# Calling function

val = oct(10.25)

# Displaying result

print("Octal value of 10.25:",val)

Output:

Output

TypeError: 'float' object cannot be interpreted as an integer

Python oct Function Example 3

In Python, both binary and hexadecimal representations are considered as integer values. Therefore, it is possible to obtain the octal conversion from binary and hexadecimal values as well. Below is an illustrative example.

Example

# Python oct() function example

# Calling function

val  = oct(0b0101) # Binary to octal

val2 = oct(0XAF) # Hexadecimal to octal

# Displaying result

# binary number

print("Octal value of 0b0101:",val)

# hexadecimal number

print("Octal value of 0XAF:",val2)

Output:

Output

Octal value of 0b0101: 0o5

Octal value of 0XAF: 0o257

Input Required

This code uses input(). Please provide values below: