[Tutor] exec sintax error or bug?

Kent Johnson kent37 at tds.net
Thu Sep 27 19:59:46 CEST 2007


paulino1 at sapo.pt wrote:
> Hello!
> 
> Why doesn't the second code snipet, work like the first?
> 
>>>> for i in range(5):
> ...    if i == 3 : continue
> ...    print i,
> ...
> 0 1 2 4
> 
>>>> exp = "if i == 3 : continue"
>>>> for i in range(5):
> ...    exec( exp )
> ...    print i,
> ...
> Traceback (most recent call last):
>    File "<input>", line 2, in <module>
>    File "<string>", line 1
> SyntaxError: 'continue' not properly in loop (<string>, line 1)

I think the code you pass to exec must be syntactically correct on its 
own. It is parsed as if it were in a file by itself, then executed in 
the local scope.

Kent


More information about the Tutor mailing list