evaluation question

Chris Angelico rosuav at gmail.com
Fri Jan 27 19:46:59 EST 2023


On Sat, 28 Jan 2023 at 11:45, <Muttley at dastardlyhq.com> wrote:
>
> Hi
>
> 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?
>

There's a difference between *expressions* (which have values) and
*statements* (which do stuff, including control flow like loops). You
may want the exec function instead.

ChrisA


More information about the Python-list mailing list