0

I have some large number of boolean values e.g

bool1 = False
bool2 = False
...
booln = False

User runs the program and provides the name of a bool to be set to True. E.g python run.py bool100. Is there a way to implement it in one or few lines without having n-depth if elif statement?

Thank you

EDIT: clarification -- these are plain bool variables and I cannot convert them into dictionaries or lists

YohanRoth
  • 2,933
  • 3
  • 21
  • 46

1 Answers1

0

Use exec to run python commands from a string

exec is a function that will let you pass a python command as a string. E.g.

exec('a = 1')
exec('print(a)') # prints 1

So the full solution is

# Create all the bools
for i in range(1, n+1):
    exec('bool{0} = False'.format(i))

# Take user input and set the bool
idx = input("Enter the bool id") # raw_input for python2
exec('bool{0} = True'.format(idx))

This has security risks in a real app. Highly discouraged. As others have mentioned, a dict should be preferred.

fizzybear
  • 1,137
  • 7
  • 20