Historic 66 Historic 66 - 2 months ago 5
Python Question

Calling a function, stored as a value in a dictionary, if the user's input matches the value's key

I'm currently creating a simple interactive fiction (IF) game in Python. In addition to the commands relevant to each room they explore, I would like for the player to have access to a list of "global commands" that can be called at anytime (inventory, help, etc).

I used this thread to get started, but I don't think it's quite what I'm looking for.

Essentially, what I want is something like this (obviously, not all of this is valid code):

def inventory():
# Shows the user's inventory

def game_help():
# shows a list of available commands

global_commands = {
'inventory': inventory(),
'help': game_help(),

command = raw_input().downcase()
if command == "get item":
print "You take the item"
elif command == "open door":
print "You open the door"
elif command in global_commands:
# execute the function that is tied to the user's input

Any and all help is appreciated!


Make the values in the global_commands dictionary the names of the functions. Don't include brackets as you don't want to call them yet.

global_commands = {
    'inventory': inventory,
    'help': game_help,

The look up the command in the dictionary and execute the procedure:

elif command in global_commands: