using break in exec()

Steve Holden steve at
Mon May 1 14:16:19 CEST 2006

Weber Matthias wrote:
> Hi,
> has anybody a suggestion to get this example to work? I have the need to 
> jump out of the loop within the exec statement.
> while True:
>     exec("break")

You can't do that, just as you can't break out of a loop by executing a 
break within a function that's called inside the loop. Python insists 
that break only occurs inside a loop construct.

You will have use some construct like

    while True:
       except SomeException:

then have your executed code raise the appropriate exception to break 
out of the loop.

If you'll forgive me saying so you seem to be relatively new to 
programming, and newcomers often make inappropriate use of "exec", which 
should really only be a last resort.

If you explain the problem in a little more depth (i.e. say exactly what 
it is you are trying to do) you might get more helpful suggestion.

Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd
Love me, love my blog
Recent Ramblings

More information about the Python-list mailing list