我正在尝试编写一个要求输入数字的程序 到雷声之间的秒数,并报告距风暴的距离 四舍五入到小数点后两位。
n = input('Enter the number of seconds between lightning and storm')
1.25
print('Distance from storm',n/5)
但是,当我调用打印函数时,出现以下错误:
Traceback (most recent call last):
File "<ipython-input-106-86c5a1884a8d>", line 1, in <module>
print('Distance from storm',n/5)
TypeError: unsupported operand type(s) for /: 'str' and 'int'
我该如何解决?
答案 0 :(得分:3)
由于您的_string
是n
,因此需要将int
转换为float
或string
(最适合您的要求):
input()
函数返回一个字符串,因此您无法应用除法,因此会出现错误:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
因此您需要对其进行转换:
n = input('Enter the number of seconds between lightning and storm')
1.25
print('Distance from storm',int(n)/5)
输出:
Distance from storm 8.6
答案 1 :(得分:1)
您可以按 int 或 float 进行输入,然后继续进行进一步的操作。
n = int(input('Enter the number of seconds between lightning and storm '))
Enter the number of seconds between lightning and storm 99
print('Distance from storm',n/5)
输出:
('Distance from storm', 19)