python - 类型错误:无法连接 'str' 和 'float' 对象

标签 python typeerror

我已经搜索过,无法弄清楚这个问题是如何产生的,或者如何解决它。感谢您的帮助,谢谢。

我的代码如下:

def main():
temperature = raw_input("Please enter an integer followed by a single space then either a F for Fahrenheit, C for Celsius, K for Kelvin, or R for Rankine: ")
    # algorithm for Farenheit to Kelvin, Celsius, and Rankine
    if temperature[-1] == "F":
    K = (temperature[:-1] + (459.67) * (5.0/9.0))
    print K
    C = (temperature[:-1] - 32) * (5.0/9.0)
    print C
    R = (temperature[:-1] + 459.67)
    print R
    # algorithm for Celsius to Kelvin, Fahrenheit, and Rankine
    elif temperature[-1] == "C":
        K = (temperature[:-1] + 273.15)
        print K
        F = (temperature[:-1] * (9.0/5.0) + 32)
        print F
        R = (temperature[:-1] + 273.15) * (9.0/5.0)
        print R
    # algorithm for Kelvin to Celsius, Fahrenheit, and Rankine
    elif temperature[-1] == "K":
        C = (temperature[:-1] - 273.15)
        print C
        F = (temperature[:-1] * (9.0/5.0) - 459.67)
        print F
        R = (temperature[:-1] * (9.0/5.0))
        print R
    # algorith for Rankine to Fahrenheit, Celsius, and Kelvin
    elif temperature[-1] == "R":
        F = (temperature[:-1] - 459.67)
        print F
        C = (temperature[:-1] - 491.67) * (5.0/9.0)
        print C
        K = (temperature[:-1] * (5.0/9.0))
        print K
main()

输入“50 F”后的错误消息:

请输入一个整数,后跟一个空格,然后输入 F(华氏度)、C(摄氏度)、K(开尔文)或 R(朗金):50 F

Traceback (most recent call last):
  File "/Users/Minotza/Documents/multi-unit_temperature_converter.py", line 36, in <module>
    main()
  File "/Users/Minotza/Documents/multi-unit_temperature_converter.py", line 5, in main
    K = (temperature[:-1] + (459.67) * (5.0/9.0))
TypeError: cannot concatenate 'str' and 'float' objects
>>> 

最佳答案

raw_input 返回用户输入的 string。您正在寻找的是 float。在 Python 中,无法将 stringfloat 对象相加。因此,您需要做的是将第一个输入转换为 float,以便您可以对其执行数学运算。

这是我将如何做到这一点:

user_input = raw_input("Prompt Text...").split(' ')

temperature = float(user_input[0])
units_or_option = user_input[1]

因此,split 方法根据用户输入的内容创建一个列表,使用空格字符拆分条目。 temperature 包含空格之前的第一个内容,转换为 floatunits_of_option 包含在数字和空格之后输入的字符。

因此,如果用户输入:

123.5 F

变量的值是:

user_input = ["123.5", "F"]
temperature = 123.5
units_or_option = "F"

关于python - 类型错误:无法连接 'str' 和 'float' 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15629098/

相关文章:

python - 是否可以使用一个整体 rate_func 运行多个动画?

hadoop - 即使我设置了 setMapOutputKey 类,但 map 中的键类型不匹配

Python 正在工作 - 没有做任何更改 - 将不再工作。可能发生了什么?

javascript - 无法读取 null react 的属性 'setState'

javascript - 未捕获的类型错误 : Object#<Object> has no method 'dispatchEvent'

python - Mayavi 如何显示轴网格

python - 如何使用 pyspark SQL 获取基于时间的累计值?

python - 如何使用 np.where 更改多个列值?

python - 构建后 session 图为空

javascript - 如何在 odoo 12 的销售点中显示弹出错误