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.
 
-Jesse
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to