为什么我会收到此输入函数的类型错误

Why am I receiving a Type error for this input function

我正在尝试编写一个请求号码的程序 闪电和雷声之间的秒数,并报告与风暴的距离 四舍五入到小数点后两位。

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'

我该如何解决?

您需要将 n 转换为 intfloat(根据您的要求),因为它是 string:

input() 函数 returns 一个字符串,因此你不能应用除法,因此错误:

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

您可以像intfloat那样接受输入,然后进行进一步的操作。

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)