类型错误:'float'对象不可下标(第 144 行)



这是我的代码:

if opt == "4":
while True:
cart_for_remove()
remove = input("Please key in the corresponding number of the item you want to remove:")
if remove.isalpha()==True:
print('Please enter a valid number!')
break
if count==0:
print('Please add item to cart first!')
break
if int(remove)<=count:
remove = int(remove) - 1
price_remove = float(cart[remove][3].strip('$ '))
total_price_final -= price_remove
savings_remove = int(total_savings[remove][2].strip('$ '))
total_savings-=savings_remove
del cart[remove]
print("Item has been successfully removed from cart!")
break
else:
print('Please choose a valid option')
break

在第 143 行之前一切都是正确的。在第 144 行,如果删除项目,我试图从总节省中删除节省,但是,出现此错误:

line 144, in <module>
savings_remove = int(total_savings[remove][2].strip('$ '))
TypeError: 'float' object is not subscriptable.

有人知道如何更正代码,以便此错误不会出现吗?

任何帮助/反馈都非常感谢。谢谢!

你看,在代码的这一部分:

if int(remove)<=count:
remove = int(remove) - 1
price_remove = float(cart[remove][3].strip('$ '))
total_price_final -= price_remove
savings_remove = int(total_savings[remove][2].strip('$ '))
total_savings-=savings_remove
del cart[remove]
print("Item has been successfully removed from cart!")
break

total_savings[remove]是一个浮子。在python中下标意味着使用方括号从元素索引的数组中获取元素。

浮点数显然是不可下标的。

最新更新