Python input interval/range

Viewed 15

I would like to make a simple program checking the range of several diffent inputs. For example, i have an online shop with 3 products, each of them has a different price - a, b and c, which are not whole numbers (float). I want when a customer is purchasing, the quantity of each product to be limited to 15. What is the best method to do this - if,else? Is it possible to be done with the range() function?

1 Answers

If all you want to do is make sure the quantity a customer orders does not exceed 15, and that limit is constant (i.e., it does not depend on what previous customers ordered), then a simple if will do the job:

if quantity_ordered > 15:
    # display some message

A slightly better practice would be not to hardwire the 15 into that code but to define a constant in advance and then use that variable, since you might want to use the limit at several places in the code, and if you hardwire it it's easy to miss one in case you want to change it later:

ORDER_LIMIT = 15

if quantity_ordered > ORDER_LIMIT:
    # display some message

(The capitalisation is a widespread Python convention for variables that are not supposed to be altered during the execution of the code.)

If, on the other hand, you want to keep track of your stockpile (initial stockpile is 15, and each order reduces it), then the most elegant solution would be to set up a dictionary that has the various products as keys, their stockpile as values, and you compare the quantity_ordered against that:

INITIAL_SUPPLY = 15

product_stockpiles = {"product_a": INITIAL_SUPPLY, "product_b": INITIAL_SUPPLY, # ...}
if quantity_ordered > product_stockpiles[selected_product]:
    # display some error message
else:
    product_stockpiles[selected_product] -= quantity_ordered
Related