【问题标题】:TypeError: unsupported operand type(s) for /: 'str' and 'float'TypeError:不支持的操作数类型/:'str'和'float'
【发布时间】:2017-08-23 16:29:53
【问题描述】:

我正在使用 Python 2,但出现错误:

TypeError:不支持的操作数类型/:'str'和'float'

当脚本运行到最后一行时。我不明白哪个变量仍然是字符串类型。

from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:') 
print 'your BMI is %r'%weight/((float(height)/100)**2)

【问题讨论】:

  • 为什么不打印出所有的变量类型和它们的值?这会立即显示出来。

标签: python python-2.7


【解决方案1】:
weight = float(weight)
height = float(height)
age = int(age)

您忘记将输入从字符串转换为数字。诊断:

print weight, type(weight)
print height, type(height)
print age, type(age)
...

【讨论】:

  • 感谢您的回复。不能在最后一行浮动(高度)将高度变成浮动类型?
  • 它当然可以——而且确实做到了。这就是您在错误消息中获得“float”类型的地方。为了便于阅读,我只是将解决方案分成小块。如果您只使用这些值一次,那么您也可以直接进行转换,而根本不转换 age
  • 如果是这样,weight 是一个'int',float(height) 是一个'float',为什么行中还有一个'str'?对不起,我一次又一次地问
  • 您是如何确定 weight 是 int 的?您的代码表明它是一个 str (所有输入都以字符串开头)。您是否按照我的建议打印了值和类型? :-)
  • 是的,我真的使用打印重量,类型(重量)来检查它,我得到 48 ,这不意味着它是一个 int 吗?
【解决方案2】:
from sys import argv
script, age, height=argv
print 'you\'re %r old'%age
weight=input('and i need your weight to calculate BMI, can you tell me:') 
print 'your BMI is %r'%(weight/((float(height)/100)**2))

我找到了解决办法,因为%后面的公式必须在()中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    相关资源
    最近更新 更多