【问题标题】:unsupported operand type(s) for /: 'str' and 'str' [duplicate]/ 不支持的操作数类型:“str”和“str”[重复]
【发布时间】:2013-08-18 16:46:26
【问题描述】:
print("Please enter your Weight")
weight = input(">")
print("Please enter your height")
height = input(">")
bmi = weight/height
if int(bmi) <= 18:
print("you are currently under weight")
elif int(bmi)>=24:
print("you are normal weight")
else:
print("you are over weight")

追溯

File "C:\Users\reazonsraj\Desktop\123.py", line 6, in <module>
bmi = weight/height
TypeError: unsupported operand type(s) for /: 'str' and 'str'

【问题讨论】:

  • 您正在输入一个字符串,然后尝试将其与字符串分开,将您的输入转换为 int
  • 使用int:int(weight)/int(height)
  • 顺便说一句,这不是您计算 BMI 的方式。

标签: python type-conversion


【解决方案1】:
print("Please enter your Weight")
weight = float(input())
print("Please enter your height")
height = float(input())
bmi = weight/height
if (bmi) <= 18:
print("you are currently under weight")
elif (bmi)>=24:
print("you are normal weight")
else:
print("you are over weight")

【讨论】:

  • 感谢一群人刚刚解决了它,并得到了正确的方法来做 bmi :)
【解决方案2】:

当输入数据时,它被保存为一个字符串。您需要做的就是将其转换为 int。

print("Please enter your Weight")
weight = int(input(">"))
print("Please enter your height")
height = int(input(">"))
bmi = weight/height
if int(bmi) <= 18:
print("you are currently under weight")
elif int(bmi)>=24:
print("you are normal weight")
else:
print("you are over weight")

这将解决一个问题,但不能解决所有问题。如果您要输入十进制数,那么您将收到ValueError,因为int() 处理整数。要解决此问题,您需要使用 float() 而不是 int。

print("Please enter your Weight")
weight = float(input(">"))
print("Please enter your height")
height = float(input(">"))
bmi = weight/height

【讨论】:

  • 但是当我输入高度为 5.5 时,它会显示此错误 ValueError: invalid literal for int() with base 10: '5.5'
【解决方案3】:
def enter_params(name):
    print("Please enter your {}".format(name))
    try:
        return int(input(">"))
    except ValueError:
        raise TypeError("Enter valid {}".format(name)) 
height = enter_params('height')
weight = enter_params('weight')
bmi = int(weight/height)
if bmi <= 18:
    print("you are currently under weight")
elif bmi >= 24:
    print("you are normal weight")
else:
    print("you are over weight")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    相关资源
    最近更新 更多