Ask coding questions

← Back to all posts
Is there a better way to find the value of multiple bool values? (python)
h
figglediggle (137)

In one of my projects, I need to test the values of 4 bool variables. Each variable can have either bool value. My current solution to this is to make an if/elif tree using the and statement to cover every possible combination of the 4 bools. To me, this seems needlessly complex. Is there a better way of testing the values?

Answered by SixBeeps (5052) [earned 5 cycles]
View Answer
Comments
hotnewtop
SixBeeps (5052)

The best way to do this is using an array instead of four separate variables. Then, you could just iterate over the array, counting how many are true and how many are false.

EpicRaisin (249)

Code for that:

bools = [False,False,False,False]
values = {1:False,2:False,3:False,4:False}
i = 1
for bool in bools:
  if(bool):
    values[i] = True
  i += 1

Then you could do some string manipulation to print which bools are true.

SixBeeps (5052)

Or if you just need to do some basic counting:

bools = [ ... ]
trueCount = 0
for bool in bools:
  trueCount += 1 if bool == True else 0
FlaminHotValdez (437)

You could use nested for loops to test every possible combination and its values.