Share your repls and programming experiences

← Back to all posts
Speed up user input with funtion arrays
ANDREWVOSS (187)

When making console apps in python, I often find myself writing user input a certain way. A message is printed that looks something like this:

1. Option 1
2. Option 2
3. Option 3
4. Option 4
5. Option 5
Select an option:

And the code would look like:

option = int(input())
if (option == 1):
  option1()
elif (option == 2):
  option2()
elif (option == 3):
  option3()
elif (option == 4):
  option4()
elif (option == 5):
  option5()

But I recently figured out a better way to do it. If, elif, else branches can be slow, so I found a way to do it without them.

options = [option1,opton2,option3,option4,option5]
option = int(input())
options[option-1]()

I'm pretty proud of this, please give feedback!