TypeError:“str”和“str”的操作数类型不受支持?

2024-10-01 17:37:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉编程,不知道如何修复此错误:

Traceback (most recent call last):
  File "/Users/aubreyoleary/Documents/Cashier.py", line 31, in <module>
    changePennies = int((amountReceived - amountDue) * 100)
TypeError: unsupported operand type(s) for -: 'str' and 'str'

我的代码:

^{pr2}$

Tags: pymost编程错误linecallusersdocuments
2条回答

这是因为amountReceivedamountDue的数据类型是字符串。在执行算术-操作之前,必须将其类型转换为float。在

不要使用int((amountReceived - amountDue) * 100),请使用:

changePennies = int(float(amountReceived) - float(amountDue)) * 100

这意味着“6”-“4”不能工作,因为它们都是字符串。首先需要将字符串值转换为数字:

changePennies = int(round((float(amountReceived) - float(amountDue)) * 100, 0))

相关问题 更多 >

    热门问题