[Tutor] RE: I don't understand why it doesn't work :(

Guillaume willblake@wanadoo.fr
Wed Jun 4 04:19:01 2003


Hi
When I type
result = eval("3*4") +  5
A little ^ points out an invalid syntax under the
"l" of evual :(
I don't know what I've done wrong.
Thanks

-----Message d'origine-----
De : Alan Gauld [mailto:alan.gauld@blueyonder.co.uk]
Envoyé : mardi 3 juin 2003 23:56
À : willblake@wanadoo.fr; Charlie Clark; tutor@python.org
Objet : Re: [Tutor] RE: I don't understand why it doesn't work :(


> I expected 17 because I tought that
> print int (s) convert my string in an integer
> so that the addition between 3*4 and 5 was possible.

But "3*4" is not a number it is an arithmetic expression.
YOu could evaluate the string and then add 5:

result = eval("3*4") + 5

But int() expects the string representation of
a number and only a number.

If you know the format of the string you could also
do:

result = int(s[0]) * int(s[-1) + 5

which converts the first and last characters of s to ints.

Or you could split the expression using the arithmetic
operators (+-*/) as the dividing characters and try to
interpret the string that way (but then that's what
eval() does for you!)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld