在python版本3.3.0中编写程序时(由于非管理特权,我无法更新),它完全正常工作,但是现在我使用的是python版本3.3.2,它不再工作了,程序如下:
num = input("please enter a value and press enter: ")(假设1被选中)
conv = input("what unit is the measurement in? cm, m, or km: ")(假设选定cm )
if conv == "cm":
print("chosen value is cm, converting to m and km")
m = num/100
print(m , "meters")
km = num/100000
print(km , "kilometers")所需的输出(见3.3.0中):
please enter value and press enter: 1
your chosen value is: 1
what unit is the measurement in? cm, m, or km: cm
you have chosen cm, converting to m and km
0.01 meters
1e-05 kilometers但我得到了(3.3.2中):
please enter value and press enter: 1
your chosen value is: 1
what unit is the measurement in? cm, m, or km: cm
you have chosen cm, converting to m and km
Traceback (most recent call last):
File "C:/Users/USER/Desktop/QUESTION.py", line 10, in <module>
m = num/100
TypeError: unsupported operand type(s) for /: 'str' and 'int'发布于 2018-03-30 02:08:44
我很惊讶它在什么地方起作用了。当使用input()函数时,Python 返回一个字符串。 (str)来自已输入的内容。
因此,基本上,您只需要在初始化了num = int(num)变量之后,使用num将文本转换为整数。为了保持干净,您还需要实现一个基本的错误处理系统,以防用户输入的输入不能隐含地转换为整数。
例如:
num = ""
while not isinstance(num, int):
num = input("Please, enter a number\n>>> ")
try:
num = int(num)
except ValueError:
pass
# proceed with your code...https://stackoverflow.com/questions/49567445
复制相似问题