[Tutor] n00b question: dictionaries and functions.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Apr 12 22:37:13 CEST 2006



On Wed, 12 Apr 2006, Jesse wrote:

> 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.


Hi Jesse,


Ah!  Yes, that's happening because there are parens in there that are 
causing the functions to fire off prematurely.


For example, let's say we have defined a function:

######
>>> def test_function(x):
...     return x * x
...
######

(I should give it a better name like square(), but let's ignore that for 
the moment.)  If we just name the function, we'll get back a function 
value:

######
>>> test_function
<function test_function at 0x81de4c4>
######

This is a value that can be stored in containers, just like any other 
Python value.


But as soon as we do use parentheses, Python will try to call the 
function:

######
>>> test_function()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: test_function() takes exactly 1 argument (0 given)
######


If we go back to the place where the commands dictionary is being built:

     commands = {"add": add(), "subtract": subtract()}

do you see what needs to be fixed to associate those strings to function 
values?


Best of wishes!


More information about the Tutor mailing list