Python oct() 函数用于将整数值转换为其八进制(以 8 为基数)表示。
与熟悉的 10 进制(十进制)不同,八进制仅使用数字 “0 到 7”。当您在 Python 中看到前缀为“0o”的数字时,例如“0o17”,则表示它是八进制表示法。
语法
以下是 python oct() 函数的语法 -
参数
此函数接受整数值作为其参数。
返回值
此函数返回一个字符串,该字符串表示给定整数的八进制值。
示例 1以下是 Python oct() 函数的示例。在这里,我们将整数 “219” 转换为它的八进制表示 -
输出
以下是上述代码的输出 -
The octal value obtained is: 0o333
示例 2
在这里,我们使用 oct() 函数检索负整数 “-99” 的八进制表示 -
输出
获得的输出如下 -
The octal value obtained is: -0o143
示例 3
现在,我们使用 oct() 函数将二进制和十六进制值转换为它们相应的八进制表示 -
输出
生成的结果如下 -
The octal value of binary number is: 0o12
The octal value of hexadecimal number is: 0o5041
The octal value of hexadecimal number is: 0o5041
示例 4
在下面的示例中,当使用 oct() 函数将整数值 “789” 转换为其八进制表示时,我们将从输出中删除 “0o” 前缀 -
输出
上述代码的输出如下 -
The octal value of the integer is: 1425
示例 5
如果我们将非整数值传递给 oct() 函数,它将引发 TypeError。
在这里,我们将通过将浮点值 “21.08” 传递给 oct() 函数来演示 TypeError -
输出
我们可以在输出中看到我们得到一个 TypeError,因为我们已经将浮点值传递给了 oct() 函数 -
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
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