TypeError: Can't convert 'float' object to str implicitly or TypeError: unsupported operand type(s)

错误代码

T_option = input("Celsius, fahrenheit, or Kelvin? ").lower()
if T_option == "celsius" or T_option == "c":
    T_C = input("Input temperature: ")
    T = (T_C - 273.15)
    print("Temp set to " + str(T) + "K")

elif T_option == "kelvin" or T_option == "k":
    T = input("Input temperature: ")
    print("Temp set to " + str(T) + "K")

elif T_option == "fahrenheit" or T_option == "f":
    T_F = input("Input temperature: ")
    T = ((T_F + 459.67) * 5/9)
    ("Temp set to  " + str(T) + "K")

改正:input()函数返回一个str对象。 在数学表达式上使用它之前,必须将该字符串转换为浮点数。

T = (float(T_C) - 273.15)

T = ((float(T_F) + 459.67) * 5/9)
结论,Python中浮点数的运算加上float(变量名)。


出处:

https://stackoverflow.com/questions/35374968/typeerror-cant-convert-float-object-to-str-implicitly-or-typeerror-unsuppor


猜你喜欢

转载自blog.csdn.net/qq_22510521/article/details/80057933