using break in exec()

Steve Holden steve at holdenweb.com
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:
       try:
          exec(your_code)
       except SomeException:
          break

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.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list