Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An alternative to many if-statements?

So I have 3 different variables.

model which is a string and defines the iPhone model.

storage which is a integer that defines the phones storage.

And finally price, which is an integer that defines the price of the phone.

Example:

model = iPhone 7
storage = 64 (GB)
price = 700 ($)

Another example:

model = iPhone 5s
storage = 16
price = 150

Now I want my program to notify me if I can make a good deal by buying and reselling, and my question is how do I do that in the most efficent way?

I know that I can use if statements, but is there any method to save me from writing alot diffrent if or elif statements?

Example:

if model == "iPhone 7" and storage == 64 and price <= 700:
print("do_something")

That's alot of code for just 1 model and storage option. If I would be using this method i'd have to write 29 more.

like image 760
Denkan Avatar asked Nov 07 '22 22:11

Denkan


1 Answers

It's normal that you have to create a "decision rule" and somehow make it accessable by your program.

1-2 tips:

You might only specify the conditions when you have to act, and you do not specify the ones where you don't do anything.

You can use dicts instead "and"s like this which leads to less code:

deal2action = {
('iphone 7', '64', '700'):'ACT'
}

Usage:

my_deal = ('iphone 7', '64', '700')
my_action = deal2action[my_deal]
like image 131
PEZO Avatar answered Nov 14 '22 20:11

PEZO