[Tutor] break and exit

Alan Gauld alan.gauld at btinternet.com
Fri Nov 21 10:41:23 CET 2014

On 21/11/14 04:10, James Rieve wrote:
> I accidently used 'exit' in a loop where I meant to use 'break' and, in that
> case, the program seemed to work as expected but in some cases 'exit' seems
> to behave differently from 'break'. For example, in this code snippet using
> 'exit' or 'break' produces the same result:
> for i in range(10):
>      if i > 3:
>          exit
>      else:
>          print(i)
> print('out of loop')

Only superficially.
When you use exit Python doesn't do anything. But it repeats that non 
operation for every number in your range(). When you use break it is 
only executed once and Python leaves the for loop immediately.
So although what is printed is the same the results in terms of the work 
Pyhon does is very different.

You can demonstrate that by adding another print message

for i in range(10):
      if i > 3:
           print("I didn't expect this!")
print('out of loop')

Now swap exit and break.

> for i in range(10):
>      if i > 3:
>          break   # try using exit here.
>      else:
>          print(i)
> else:
>      print('for loop else statement')
> print('out of loop')

Because the for/else is only executed if the loop completes
normally - which it does with exit - so a break will bypass
that for/else clause.

> Does anyone have any pointers to descriptions of 'exit', what it is,

Its the name of a function. So using it in isolation like that has the 
same effect as just putting any variable name on its own does:

for n in range(5):
else: print('loop completed')

The use of n here is like your use of exit. Its just a name.

But if you called exit using () the effect would be quite different
to break. It would then exit your whole program.

Alan G
Author of the Learn to Program web site
Follow my phopto-blog on Flickr at:

More information about the Tutor mailing list