Python:如何在后续减法中使用divmod中的值

问题描述 投票:-1回答:1

如何将divmod除法的结果包含在一个简单的减法中,而不是面对:TypeError:不支持的操作数类型 - :'int'和'tuple'?

这是我的代码(用Python编写):

def discount(price, quantity): 
if (price > 100): 
    discounted_price = price*0.9
else: 
    discounted_price = price

if (quantity > 10): 
    deducted_quantity = divmod(quantity, 5)
    discounted_quantity = quantity - deducted_quantity
else: 
    discounted_quantity = quantity

#Compute which discount yields a better outcome   
if (discounted_price*quantity < price*discounted_quantity):
    return(discounted_price*quantity)
else:
    return(price*discounted_quantity)

任何帮助都非常受欢迎,因为我是初学者,我还找不到合适的解决方案。

仅供您参考的基础任务:编写一个函数discount(),它接受(位置)参数的价格和数量,并为客户订单实施折扣方案,如下所示。如果价格超过100美元,我们会给予10%的相对折扣。如果客户订购的物品超过10件,则每五件物品中就有一件是免费的。然后该功能应返回总成本。此外,只授予两种折扣类型中的一种,以客户为准。

Error in full length

python typeerror divmod
1个回答
1
投票

divmod返回一个元组(d, m),其中d是除法的整数结果(x // y),m是余数(x % y),使用索引来获得你想要的两个(divmod):

deducted_quantity = divmod(quantity, 5)[0]
# or:
# deducted_quantity = divmod(quantity, 5)[1]

或者如果您需要两者,请使用解包为每个值使用变量:

the_div, the_mod = divmod(quantity, 5)
© www.soinside.com 2019 - 2024. All rights reserved.