evaluation question
dn
PythonList at DancesWithMice.info
Fri Jan 27 20:22:01 EST 2023
On 28/01/2023 05.37, Muttley at dastardlyhq.com wrote:
> This is probably a dumb newbie question but I've just started to learn
> python3 and eval() isn't behaving as I'd expect in that it works for
> some things and not others. eg:
>
>>>> eval("1+1")
> 2
>>>> eval("print(123)")
> 123
>>>> eval("for i in range(1,10): i")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<string>", line 1
> for i in range(1,10): i
> ^
> SyntaxError: invalid syntax
>
> Why did the 3rd one fail? Does it not handle complex expressions?
eval() is very powerful, and therefore rather dangerous in the risks it
presents.
Thus, seems a strange/advanced question for a "newbie" to be asking. YMMV!
Do you know about the Python REPL?
If you open python within a terminal, each of the three
expressions/compound-statements listed will work, as desired, without
eval().
dn $ ... python
Python 3.11.1 (main, Jan 6 2023, 00:00:00) [GCC 12.2.1 20221121 (Red
Hat 12.2.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
>>> print( 123 )
123
>>> for i in range( 1, 10 ): i
...
1
2
3
4
5
6
7
8
9
>>> exit()
--
Regards,
=dn
More information about the Python-list
mailing list