-1

I am making a program in Python 3.5 which will run different functions when you enter different inputs:

commandList = ["test1", "test2", "test3"]
def test1():
    print("TEST 1 FUNCTION")
def test2():
    print("TEST 2 FUNCTION")
def test3():
    print("TEST 3 FUNCTION")
while True:
    userRaw = input(">:")
    user = userRaw.lower()
    for x in range(len(commandList)):
        if user == commandList[x]:
            # Needs to run function which has the same name as the string 'user'
            # E.g. if user = 'test1' then function test1() is run.

What would I need to enter after the if statement (where the comments are)?

I have tried doing something like this, but it has not worked:

commandList = ["test1", "test2", "test3"]
def function(test1):
    print("TEST 1 FUNCTION")
def function(test2):
    print("TEST 2 FUNCTION")
def function(test3):
    print("TEST 3 FUNCTION")
while True:
    userRaw = input(">:")
    user = userRaw.lower()
    for x in range(len(commandList)):
        if user == commandList[x]:
            function(user)

I am trying to avoid a lots of if statements as I aim to make my code easily scalable (quickly add new functions).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

1 Answers1

5

You named your functions in the same name, so it probably shouldn't work.

But let's make it even better. Use a dictionary:

def function1():
   print('foo')

def bad_choice():
    print('Too bad')
...

function_mapper = {'test1': function1, 'test2': function2, 'test3': function3}
user_input = input('Please enter your choice: ')
chosen_function = function_mapper.get(user_input, bad_choice)
chosen_function()
cs95
  • 379,657
  • 97
  • 704
  • 746
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64
  • Thanks for answering, but I think I will the answer from @Coldspeed as it is more concise – Logan Miller Jun 22 '17 at 19:33
  • @LoganMiller It may seem more concise today, but in 6 months when you come back to look at your code and struggle to understand what is going on you may wish you went with this answer instead. In general, when programming, taking the fast solution today will make it harder to debug tomorrow. – SethMMorton Jun 22 '17 at 20:21