首页 > 解决方案 > Python 无法将浮点对象隐式转换为 str

问题描述

我正在尝试编写一个将英里转换为码英尺和英寸的程序,但我遇到了问题。我使用 Flogorithm 将代码放在一起,但出现错误“变量脚未初始化”。然后我把它放到 cloud9 中测试代码,我得到了错误:

line 22, in <module>
    calculateyards (miles)
line 15, in calculateyards
    print("The result is" + yards)
TypeError: Can't convert 'float' object to str implicitly

代码是:

def calculatefeet(miles, feet):
    feet = miles * 1760
    print("The result is" + feet)

    return feet

def calculateinches(miles, inches):
    inches = miles * 63360

    return inches

def calculateyards(yards):
    miles = float(input())
    yards = miles * 1760
    print("The result is" + yards)

    return yards

# Main
print("enter a distance in miles")
miles = float(input())
calculateyards (miles)
calculatefeet (miles, feet)
calculateinches (miles)

我真的不擅长函数调用,这就是为什么我遇到这么多问题并且需要帮助的原因。

标签: python-3.x

解决方案


+Python 是一种强类型语言,因此当连接运算符期望两个操作数都是字符串时,没有从 float 到 str 的隐式转换。

str()您应该使用构造函数将浮点变量转换为字符串:

print("The result is " + str(yards))

或使用以下str.format方法:

print("The result is {}".format(yards))

推荐阅读