'Python 3 Jump Tables

I am trying to figure out how to create a basic jump table, so I can better understand different ways of creating menus in Python 3.5.6. Here is what I have so far:

def command():
    selection = input("Please enter your selection: ")
    return selection

def one():
    print ("you have selected menu option one")

def two():
    print ("you have selected menu option two")

def three():
    print ("you have selected menu option three")

def runCommand(command):
    jumpTable = 0
    jumpTable[command]()
    jumpTable = {}
    jumpTable['1'] = one
    jumpTable['2'] = two
    jumpTable['3'] = three

def main():
    command()
    runCommand(command)

if __name__ == "__main__":
    main()

As far as I understand, a jump table is simply a way of making a menu selection and calling a specific function associated with that numerical value, taken in by my "command" function. Within the jumpTable, you assign the function to call.

I am getting " File "omitted", line 16, in runCommandjumpTableone TypeError: 'int' object is not subscriptable

All I want to do is have the user enter a number - 1, 2 or 3 and have that function run. when I get this basic functionality down, I will expand the menu to show the options and be more clear. I just need to get the darn thing to run!

Yes, I am aware of other ways to create menus (IF/ELIF/ELSE) I am just trying to nail this one down!

Thank you in advance!



Solution 1:[1]

You are quite close. The only issue is that you are trying to access the command before creating the jumpTable. And I am also not sure why you are setting the variable to 0 first (that's why you get the int is not subscriptible error). So, this is the right order:

def runCommand(command):
    jumpTable = {}
    jumpTable['1'] = one
    jumpTable['2'] = two
    jumpTable['3'] = three
    jumpTable[command]()

By the way, if you are always creating the same jumpTable, you could create it once, outside the function and simply call jumpTable[command]() in your main function.

Another problem: you should store the value you get from the user and pass that to the next function like this:

cmd = command()
runCommand(cmd)

, or simply pipe the two functions together like this:

runCommand(command())

Solution 2:[2]

"""
Based on the original question, the following will.
Add a menu to a console application to manage activities.
Run a selected function.
Clear the output 
Display the menu again or exit if done is selected
"""
import sys
from os import system


def display_menu(menu):
    """
    Display a menu where the key identifies the name of a function.
    :param menu: dictionary, key identifies a value which is a function name
    :return:
    """
    for k, function in menu.items():
        print(k, function.__name__)


def one():
    print("you have selected menu option one")
    input("Press any Enter to return to menu.")
    system('cls') # clears stdout


def two():
    print("you have selected menu option two")
    input("Press any Enter to return to menu.")
    system('cls') # clears stdout


def three():
    print("you have selected menu option three")
    input("Press any Enter to return to menu.")
    system('cls') # clears stdout


def done():
    system('cls') # clears stdout
    print("Goodbye")
    sys.exit()


def main():
    # Create a menu dictionary where the key is an integer number and the
    # value is a function name.
    functions_names = [one, two, three, done]
    menu_items = dict(enumerate(functions_names, start=1))

    while True:
        display_menu(menu_items)
        selection = int(
            input("Please enter your selection number: "))  # Get function name
        selected_value = menu_items[selection] # Gets the function name
        selected_value()  # add parentheses to call the function


if __name__ == "__main__":
    main()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zsomko
Solution 2