jeudi 7 octobre 2021

Combine multiple if else statement

I have made a functionality wherein if the value of the commodity increase by 1 percent the threshold value also increases by 1 percent. The best case here would be to use switch statement in python. But there are none in python as mentioned at Replacements for switch statement in Python?

Hence I used multiple if else and elif statements in python. PFA the code as below:

price = 100.0

price = 100.0

Price=104

threshold=90.0

if Price == 1.01*price:
    threshold=1.01*threshold

elif Price == 1.02*price:
    threshold=1.02*threshold

elif Price==1.03*price:
    threshold=1.03*threshold

else:
    threshold=1.04*threshold
    

Hence the output I get by above programme is:

price   Price   Threshold
100     100     93.6
100     101     90.9
100     102     91.8
100     103     92.7
100     104     93.6

Do note that this is just an example shown. In real Scenario the Price value gets updated every 1 second

My question is I use multiple if and elif statements in the programme. So is there a way to combine these multiple if and elif statements so as to make the code shorter and cover all the scenarios?

Aucun commentaire:

Enregistrer un commentaire