python-3.x - 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 是一种强类型语言,因此当连接运算符期望两个操作数都是字符串时,没有从 float 到 str 的隐式转换。
str()
您应该使用构造函数将浮点变量转换为字符串:
print("The result is " + str(yards))
或使用以下str.format
方法:
print("The result is {}".format(yards))
推荐阅读
- autocomplete - VSCode 中完整的 Markdown 文件路径
- android - 一起启动两个动画
- parsing - 批处理脚本:解析文件并获取特定的行号子字符串
- c - C 编程:字符串数组 - 如何检查相等性?
- c# - Unity 语法错误 按空格键时 LaserSound 不播放?
- shell - sh,读取大量日志文件并 grep 一些文本并打印所有出现的文件名和行号
- java - 如何在 Maybe.create(emitter) 中发出 Maybe.empty?
- python - 如何从数组中选择数据以绘制图形
- javascript - 第二次执行遵循href
- python - 如何比较第一列和第二列