Home > Blockchain >  Multiple IF statements in Python in a for loop or while loop?
Multiple IF statements in Python in a for loop or while loop?

Time:07-01

Let's say I buy a certain volume of petrol at price X, which is usually sold within a 30 days. During these 30 days, I will need to adjust my petrol station gas price according to average State gas price. If State price goes up by 1.2% from my purchased price, I will set my price to 1% of my purchased price.

Here is a python code but it is very clunky, and if gas price moves up by 20%, then I have to write my_priceX up to 20 times. Is there a more elegant solution?

my_price1 = last_gas_price["price"]*1.01 
my_price2 = last_gas_price["price"]*1.02 
my_price3 = last_gas_price["price"]*1.03 
my_price4 = last_gas_price["price"]*1.04  
my_price5 = last_gas_price["price"]*1.05 

if last_gas_price > my_price1:
    adj_price(price = my_price1)

if last_gas_price > my_price2:
    adj_price(price = my_price2)

if last_gas_price > my_price3:
    adj_price(price = my_price3)

if last_gas_price > my_price4:
    adj_price(price = my_price4)

if last_gas_price > my_price5:
    adj_price(price = my_price5)

CodePudding user response:

Use a loop over the multipliers:

for multiplier in (1.01, 1.02, 1.03, 1.04, 1.05):
    if last_gas_price > last_gas_price["price"]*multiplier:
        adj_price(price=last_gas_price["price"]*multiplier)

With 3.8 's walrus operator you can avoid redoing the multiplication if you really care:

for multiplier in (1.01, 1.02, 1.03, 1.04, 1.05):
    if last_gas_price > (myprice := last_gas_price["price"]*multiplier):
        adj_price(price=myprice)

If you only need to run adj_price once, for the highest passing multiplier, run the loop in reverse and break when you get a hit:

for multiplier in (1.05, 1.04, 1.03, 1.02, 1.01):  # Reversed multipliers
    if last_gas_price > (myprice := last_gas_price["price"]*multiplier):
        adj_price(price=myprice)
        break  # Found highest passing multiplier and adjusted, now we're done

Note: The code you provided is clearly wrong (last_gas_price is a dict initially, then apparently a scalar, probably float, later). This new code replicates that mistake. You'd need to adjust the variable names used to separate the dict usage from the non-dict usage appropriately.

CodePudding user response:

OK, This situation as I see is pretty disordered, and as ifs are increazing per my_prize, use a for loop so you say as prize increases, set it as is it.

  • Related