oct()函数以及Python中的示例
Pythonoct()功能
oct()函数是一个库函数,用于获取给定数字的八进制值,它接受整数并以字符串格式返回其八进制值。
语法:
oct(number)
Parameter(s):number-一个整数,其值将转换为八进制数。
返回值:str–以字符串格式返回转换后的数字八进制值。
示例
Input: num = 12345 print("octal value of ", num, " is = ", oct(num)) Output: octal value of 12345 is = 0o30071
示例1:Python代码以八进制格式转换数字
#python代码演示示例 # oct() number #数 num = 12345 print("octal value of ", num, " is = ", oct(num)) num = 0 print("octal value of ", num, " is = ", oct(num)) num = 2712 print("octal value of ", num, " is = ", oct(num))
输出结果
octal value of 12345 is = 0o30071 octal value of 0 is = 0o0 octal value of 2712 is = 0o5230
示例2:用于打印返回类型的Python代码oct()输入错误的功能并测试功能
#python代码演示示例 # oct() number #数 num = 12345 # printing return type of the function oct()print("return type is: ", type(oct(num))) #用无效值测试 print(oct(10.23)) #返回错误,因为它是一个浮点值
输出结果
return type is: <class 'str'> Traceback (most recent call last): File "/home/main.py", line 11, in <module> print(oct(10.23)) #返回错误,因为它是浮动值 TypeError: 'float' object cannot be interpreted as an integer