Python: How to use values from divmod in a subsequent subtraction

616 views Asked by At

how do I include the result of a divmod division into a simple subtraction without facing: TypeError: unsupported operand type(s) for -: 'int' and 'tuple'?

Here my code (written in 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)

Any help is highly appreciated since I am a beginner and I could not find a fitting solution yet.

Just for your information the underlying task: Write a function discount() that takes (positional) arguments price and quantity and implements a discount scheme for a customer order as follows. If the price is over 100 Dollars, we grant 10% relative discount. If a customers orders more than 10 items, one in every five items is for free. The function should then return the overall cost. Further, only one of the two discount types is granted, whichever is better for the customer.

Error in full length

1

There are 1 answers

0
DjaouadNM On BEST ANSWER

divmod returns a tuple (d, m) where d is the integer result of the division (x // y) and m is the remainder (x % y), use indexing to get whatever it is you want of the two (div or mod):

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

Or if you need both, use a variable for each value using unpacking:

the_div, the_mod = divmod(quantity, 5)