【问题标题】:Subtracting From Variables - Thonny Python从变量中减去 - Thonny Python
【发布时间】:2021-01-12 14:57:03
【问题描述】:

我在 python 中需要减法方面的帮助。

对发生的事情的回应在这里:

Traceback (most recent call last):
  File "/home/pi/Desktop/TheBacsShop.py", line 16, in <module>
    balance_a -= 40
TypeError: unsupported operand type(s) for -=: 'str' and 'int'
>>> 

这是我写的:

balance_a -= 40

我真的不知道我的代码有什么问题。如果你不知道我想做什么。我会解释:

所以基本上我希望“玩家的平衡”从任何数字 ABOVE 40 开始。但然后从中减去 40。没有设置它的东西。我会做些什么来实现它?

(无论我在做什么都可能是正确的,只是在 THONNY PYTHON 中不可用)

[编辑]:天哪,你给我的第一个遮阳篷是正确的。但随后(提示失败音乐)ANOTHER ERROR 出现了?!?!?!

【问题讨论】:

  • 检查balance_a的类型,应该是int。
  • 我的猜测是您在忽略显示的代码中的某处使用了input(),而不是int(input())。如果您想要的不仅仅是猜测,请提供minimal reproducible example
  • 具体;如果您不告诉我们您遇到了什么错误,“另一个错误”就没有任何意义。
  • 哦,这是一个老生常谈的玩笑。再加上另一个错误出现了。 \/ \/ \/ \/ (下面是什么错误。)

标签: python string integer thonny


【解决方案1】:

错误

TypeError: unsupported operand type(s) for -=: 'str' and 'int'

告诉你balance_a 是一个str(类型字符串)而不是一个int(类型整数)。您需要确保 balance_a 是一个整数。例如,'3' 是一个字符串; 3 是一个整数。

int(balance_a) 会将字符串 ('3') 转换为整数 (3),然后您可以将其用于减法。

您要查找的最终代码是:

balance_a = int(balance_a) - int(gunCost)
print("You balance is now: $" + str(balance_a) + ".") 

【讨论】:

    【解决方案2】:

    在算术运算之前将变量转换为int

    balance_a = int(balance_a)
    

    【讨论】:

      【解决方案3】:

      @Timur Shatland 等等,什么?

      我将如何设置减法它是自我

      因为我已经把'int'放在它前面了。现在我该怎么办?喜欢这里: balance_a = int(balance_a [What do I put here? eg - or 'minus' or what?] gunCost

      如果您不完全理解,请说。

      (这不是另一个遮阳篷)

      【讨论】:

      • 您可以使用“添加评论”链接而不是创建新答案(或编辑原始问题)。这是您需要的代码:balance_a = int(balance_a) - int(gunCost)(如果 gunCost 也是一个字符串)。
      • 是的,然后发生这种情况: print("You balance is now: $" + balance_a + ".") TypeError: can only concatenate str (not "int") to str >>>
      • 没错。您不能将整数 (balance_a) 与字符串 ('Your....') 连接起来。这次你需要将 balance_a 转换成字符串:str(balance_a)
      • 我已经用完整的代码更新了我的答案。如果这回答/解决了您的问题,请接受它。
      • 是的,非常感谢! (成功了)现在我必须为其他产品复制这种脑力 3 次 xD
      猜你喜欢
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多