Reputation: 5388
I am trying to create a complex if else statement in python. These statements should check two variables. The sample code:
if value1 == 0.1 and value2 > 2.05:
value1 = value1 + 0.1
return value1
elif value1 == 0.2 and value2 > 1.85:
value1 = value1 + 0.1
elif value1 == 0.3 and value2 > 1.95:
value1 = value1 + 0.1
elif value1 == 0.4 and value2 > 2.05:
value1 = value1 + 0.1
...
if value1 == 0.1 and value2 < 1.75:
return value1
elif value1 == 0.2 and value2 < 1.85:
value1 = value1 - 0.1
elif value1 == 0.3 and value2 < 1.95:
value1 = value1 - 0.1
elif value1 == 0.4 and value2 < 2.05:
value1 = value1 - 0.1
....
In total I have an if or elif for every value1 from 0.1 - 1. Every time value2 is a different value. What I want to do is to check also if value2 is less than a value in order to decrease value1 = value -1
. Which is the most clever way to do so, without adding many if -elif statements?
Upvotes: 1
Views: 615
Reputation: 21193
If there is no pattern or it's so complex that it can't be easily constructed with a loop then I would do something like this:
eq_gt_pairs = ((0.1, 2.05), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...
eq_lt_pairs = ((0.1, 1.75), (0.2, 1.85), (0.3, 1.95), (0.4, 2.05)) # ...
for pair in eq_gt_pairs:
if value1 == pair[0] and value2 > pair[1]:
return value1 + 0.1
for pair in eq_lt_pairs:
if value1 == pair[0] and value2 < pair[1]:
return value1 - 0.1
Upvotes: 4