-1

I declared 3 functions earlier, this is just a goofy text based cookie clicker-esque game.

dostuff={"" : turn() , "help" : helpf() , "invest" : invest() }
while done != True:<br>
    do = input("What do you want to do? ")
    do = do.lower()
    if do == "" or do == "help" or do == "invest":
        dostuff[do]
    elif do == "quit":
        done = True

So when I use dostuff["turn"] it does nothing (the function is supposed to print some things). I have the same problem with the other options.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Gage
  • 1
  • 1
    Possible duplicate of [Calling a function of a module from a string with the function's name in Python](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) – TemporalWolf Jun 28 '16 at 20:20

1 Answers1

6

Your parentheses must be omitted in the dict, and then put at the end of the dict call. You define a function, which becomes a python object. You reference the object with the dict, and then you call the function with the object reference followed by parentheses:

def one():
    print("one")

def two():
    print("two")

do_stuff = {
    "one": one,
    "two": two
}

do_stuff["one"]()

prints:

"one"

You can take this concept of executing calls with string inputs a lot farther by familiarizing yourself with the builtin functions of python.

https://docs.python.org/2/library/functions.html

For example, you can create a class and call its methods or properties using text based input with the getattr method:

class do_stuff():
    def __init__(self):
        pass

    def one(self):
        print("one")

    def two(self):
        print("two")

doer = do_stuff()
inp = "one"

getattr(doer, inp)()

prints->

"one"
Vince W.
  • 3,561
  • 3
  • 31
  • 59