Reputation: 581
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.
code:
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
Here:
price = initial price of commodity
Price = price after we buy quantity. Keeps changing every min
Threshold = minimum price which the commodity can reach. If the price of the commodity goes below this threshold we sell the commodity.
What I mean to attain by implementing this functionality is that a unit percent increase in the Price of the commodity should increase the threshold by same unit percent.Nothing should be done to the threshold if the Price of the commodity goes below the original buyprice.
Hence when the price of the commodity goes to 101 which is 1 percent increase in the price of the commodity the threshold also increases by same amount. if the Price of the commodity increases to 2 percent the threshold also increases by 2 percent of original threshold value 2 percent increase in 90 is 91.8 If the buyprice decreases by 1 percent that is becomes 99 the threshold stays same that is 90. If the price goes on decreasing and goes below threshold we sell commodity.
Now
Hence the output I get by above programme is:
price Price Threshold
100 101 90.9
100 102 91.8
100 103 92.7
100 104 93.6
100. 99. 90
100. 96 90
100. 91. 90
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?
Upvotes: 0
Views: 264
Reputation: 302
If you don't mind to upgrade your pyhon, in python 3.10 they have incorporated switch-case pattern matching. https://docs.python.org/3.10/whatsnew/3.10.html
However, I would use a loop for that and use more abstract coding for that purpose.
if Price == (1+increase)*price:
threshold = (1+increase)*price
Where increase is that percentage that you want to add to your Price. Given that increase you can just check when the price has risen to that increment and update threshold.
Another way would be to just
increase= Price/price
However, I have not tested it so give it a try! ;)
Upvotes: 2