You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Python车辆类代码时出现TypeError: must be a real number, not a tuple错误如何解决?

解决TypeError: must be a real number, not a tuple错误

错误原因

你在为car1.value和car2.value赋值时使用了逗号(如60,000.00),Python会将这种语法解析为元组(例如60,000.00实际被处理为(60, 0.0))。而格式化字符串中的%.2f格式符要求传入实数(整数或浮点数),因此触发了类型不匹配的错误。

修复方案

Python中表示带千位分隔的数字不能用逗号,有两种正确写法:

  • 直接书写完整数字(如60000.00)
  • 使用下划线作为千位分隔符(Python 3.6+支持,如60_000.00),下划线不会影响数值解析,仅用于提高可读性

修复后的完整代码

class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str

car1 = Vehicle()
car1.name = "Fer"
car1.color = "Red"
car1.kind = "Convertible"
car1.value = 60000.00  # 移除逗号,直接赋值浮点数

car2 = Vehicle()
car2.name = "Jump"
car2.color = "Blue"
car2.kind = "Van"
car2.value = 10000.00  # 移除逗号,直接赋值浮点数

print(car1.description())
print(car2.description())

运行结果

Fer is a Red Convertible worth $60000.00.
Jump is a Blue Van worth $10000.00.

内容的提问来源于stack exchange,提问作者Mohammad Hasan Azhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:05:15