+ 2

In python, is there a way to make an if statement run if a certain number of any of the given conditions are satisfied?

For example, if I give 5 conditions and want the code to run if any 3 of these conditions are true. I have never come across anything to do this, so I'm just curious if there is some way to do this.

1st May 2017, 8:32 AM
Swapnodip
Swapnodip - avatar
3 odpowiedzi
+ 14
Not good with Python syntax, so I'll just be using C++ syntax to explain the algorithm: int truth_count = 0; bool conditions[5]; // codes to alter the conditions for (int i = 0; i < 5; i++) { if (condition[i]) { truth_count++; } } if (truth_count >= 3) { // do something } In the above codes, we use a loop to check all the conditions, and increment the counter for each true condition. If the counter is more than or equal to 3, the block of code following the evaluation runs.
1st May 2017, 8:51 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
One thing you can simply do is put 'or' operation between the condition inside your if statement. This will make sure that your if-block runs if any of the condition satisfies. For three condition to be satisfied put 'and' operation between them and 'or' operation among the remaining condition. Happy coding...
1st May 2017, 9:12 AM
Rishabh Agrawal
Rishabh Agrawal - avatar
+ 1
When you check you 5 conditions make sure you keep your values into variables, after that you can easily check whether 3 of those are true. Or, if I understand you correctly you should separate your 3 If statements with && (logical-and) and another two if statements with || (logical-or). If this part is false, then 3 conditions were false, because logical-and will be True, when all conditions around it are True.
1st May 2017, 9:21 AM
Ani Naslyan
Ani Naslyan - avatar