【问题标题】:Why am I receiving a Type error for this input function为什么我收到此输入函数的类型错误
【发布时间】:2019-01-29 14:04:17
【问题描述】:

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

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'

我该如何解决这个问题?

【问题讨论】:

标签: python function input spyder


【解决方案1】:

您需要将您的n 转换为intfloat(只要符合您的要求),因为它是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.25 吗?
  • @RoelvanEndhoven 这取决于 OP 需要什么。
  • 我仍然收到一个错误:在 [109]: print('Distance from Storm',int(n)/5) Traceback (last recent call last): File "", line 1, in print('Distance fromstorm',int(n)/5) ValueError: invalid literal for int() with base 10: '1.25'
【解决方案2】:

您可以像 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多