Python oct() 函式



Python 的oct()函式用於將整數轉換為其八進位制(基數 8)表示。

與熟悉的十進位制(基數 10)系統(範圍從 0 到 9)不同,八進位制僅使用數字“0 到 7”。在 Python 中,如果看到一個以“0o”為字首的數字,例如 '0o17',則表示它是八進位制表示。

語法

以下是 python oct() 函式的語法:

oct(x)

引數

此函式接受一個整數值作為引數。

返回值

此函式返回一個字串,表示給定整數的八進位制值。

示例 1

以下是 Python oct() 函式的示例。這裡,我們將整數“219”轉換為其八進位制表示:

integer_number = 219
octal_number = oct(integer_number)
print('The octal value obtained is:', octal_number)

輸出

以上程式碼的輸出如下:

The octal value obtained is: 0o333

示例 2

這裡,我們使用 oct() 函式獲取負整數“-99”的八進位制表示:

negative_integer_number = -99
octal_number = oct(negative_integer_number)
print('The octal value obtained is:', octal_number)

輸出

獲得的輸出如下:

The octal value obtained is: -0o143

示例 3

現在,我們使用 oct() 函式將二進位制值和十六進位制值轉換為其對應的八進位制表示:

binary_number = 0b1010
hexadecimal_number = 0xA21
binary_to_octal = oct(binary_number)
hexadecimal_to_octal = oct(hexadecimal_number)
print('The octal value of binary number is:', binary_to_octal)
print('The octal value of hexadecimal number is:', hexadecimal_to_octal)

輸出

產生的結果如下:

The octal value of binary number is: 0o12
The octal value of hexadecimal number is: 0o5041

示例 4

在下面的示例中,我們使用 oct() 函式將整數“789”轉換為其八進位制表示時,將去除“0o”字首:

integer_number = 789
octal_noprefix = oct(integer_number)[2:]
print('The octal value of the integer without prefix is:', octal_noprefix)

輸出

以上程式碼的輸出如下:

The octal value of the integer is: 1425

示例 5

如果我們將非整數值傳遞給 oct() 函式,它將引發 TypeError。

這裡我們將透過將浮點值“21.08”傳遞給 oct() 函式來演示 TypeError:

# Example to demonstrate TypeError
floating_number = 21.08
octal_number = oct(floating_number)
print('The octal value of the floating number is:', octal_number)

輸出

我們可以從輸出中看到,因為我們向 oct() 函式傳遞了一個浮點值,所以我們得到了一個 TypeError:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    octal_number = oct(floating_number)
TypeError: 'float' object cannot be interpreted as an integer
python_type_casting.htm
廣告