[Tutor] n00b question: dictionaries and functions.
Bob Gailer
bgailer at alum.rpi.edu
Wed Apr 12 22:40:56 CEST 2006
Jesse wrote:
> Hey, this should be an easy question for you guys. I'm writing my
> first program (which Bob, Alan, and Danny have already helped me
> with--thanks, guys!), and I'm trying to create a simple command-line
> interface. I have a good portion of the program's "core functions"
> already written, and I want to create a dictionary of functions. When
> the program starts up, a global variable named command will be
> assigned the value of whatever the user types:
>
> command = raw_input("Cmd > ")
>
> If command is equivalent to a key in the dictionary of functions, that
> key's function will be called. Here's an example that I wrote for the
> sake of isolating the problem:
>
>
> def add():
> x = float(raw_input("Enter a number: "))
> y = float(raw_input("And a second number: "))
> print x + y
> def subtract():
> x = float(raw_input("Enter a number: "))
> y = float(raw_input("And a second number: "))
> print x - y
>
>
> commands = {"add": add(), "subtract": subtract()}
>
>
>
> Now, before I could even get to writing the while loop that would take
> a command and call the function associated with that command in the
> commands dictionary, I ran this bit of code and, to my dismay, both
> add() and subtract() were called. So I tried the following:
>
> def add(x, y):
> x = float(raw_input("Enter a numer: "))
> y = float(raw_input("And a second number: "))
> add = add()
>
> When I ran this, add() was called. I don't understand why, though.
> Surely I didn't call add(), I merely stored the function call in the
> name add. I would expect the following code to call add:
>
> def add(x, y):
> x = float(raw_input("Enter a numer: "))
> y = float(raw_input("And a second number: "))
> add = add()
> add
>
> Can someone clear up my misunderstanding here? I don't want to end up
> writing a long while loop of conditional statements just to effect a
> command-line interface.
"stored the function call" NO - this mixing 2 things. What you want is
to store a reference to the function, then call the function thru its
reference in response to user input. add is a reference to the function.
add() calls (runs) the function.
commands = {"add": add, "subtract": subtract} # stores function references
command = raw_input("Cmd > ")
if command in commands:
commands[command]() # retrieve a function reference and calls it.
More information about the Tutor
mailing list