[Tutor] name is not defined error

Alan Gauld alan.gauld at btinternet.com
Sun Oct 29 18:37:26 CET 2006


"Kristinn Didriksson" <kdidriksson at gmail.com> wrote
> I am trying to solve the following exercise and get a name is not
> defined error. It is my understanding that eval turns a string into 
> a
> number and then I can do math operations on it.

Not really. eval takes a string and interprets it as a
python expression. Thus you can do things like:

>>> a = 6
>>> b = 9
>>> eval("a+b")
15

So eval recognised a and b as local variables and added them
together. But if I now try:

>>> eval("c+d")

I get an error because Python doesn't know about c or d.

Because Python will try to evaluate and string as a piece
of python it is potentially dangerous and a security risk
since the code it evaluates could be malicious code. For
that reason you should be very careful about how you use
eval, and its partner exec, usually there are better alternatives.

> # Numerology. Calculate the numeric value of a name. a =1, b=1,...z 
> = 26
> # Add the values for each letter for a total.

You will need more than a comment, you will need to actually
create variables for each of the letters of the alphabet.
Either manually:

a = 1
b = 2

or using a loop and exec:

import string
for ch in string.lowercase:
    command = "%s = ord('%s') - ord('a') + 1" % (ch,ch)
    exec(command)

Or to avoid using the risky exec call, you could use a dictionary:

vals = {}
for ch in string.lowercase:
    vals[ch] = ord(ch) - ord('a') + 1


> name = raw_input("Please enter your name: ")
>
> totalValue = 0
> for eachLetter in string.lower(name):
>    numEquiv = eval(eachLetter)
>    letterValue = numEquiv -96  # not sure why you subratact 96...
>    totalValue = totalValue + numEquiv

Of course a little thought will show that you could do the
whole thing with ord and not use eval at all! That also removes
the need for the list of variables.

But I'll leave that as an exercise :-)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list