I am having trouble understanding what is happening with the following function:
def ness(): pie='yum' vars()[pie]=4 print vars()[pie] print yum
So, when I run, I get this result:
>>> ness() 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in ness NameError: global name 'yum' is not defined
If I do not write it as a function and just type it on the command line one line at a time, it works fine:
>>> pie='yum' >>> vars()[pie]=4 >>> print vars()[pie] 4 >>> print yum 4 >>>
Edit: Suppose I wanted to make things a little more complicated than that, and instead of setting yum to a value and printing that value, I define some functions and want to name one of them based on some input:
def ness(choo): dic={} dessert=() dnum=[10,100] desserts='pie' dic[dessert]=str(desserts[bisect(dnum,choo)]) vars()[dic[dessert]]() def p(): print 'ummmm ummm' def i(): print 'hooo aaaaa' def e(): print 'woooo'
Therefore, when I call ness, I get a key error:
>>> ness(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in ness KeyError: 'p'
Now I know that I can do something like this with some elif statements, but I wonder if this will work, and if using bisect like this would be more efficient (say if I need to check 1000 choo values) than using elifs .
Many thanks for the help.