[Tutor] Python Help - How to end program

Alan Gauld alan.gauld at btinternet.com
Thu Jul 29 10:07:46 CEST 2010


"Jason MacFiggen" <jmacfiggen at gmail.com> wrote

> Python keeps looping when it gets past the int 0, how do I end the 
> program
> when it the int 0 or > 0.
>
>    while True:
>        if mo_hp < 0:
>            print "The Lich King has been slain!"
>        elif my_hp < 0:

/etc...

When using a while True loop you need ttto have an explicit break
statement somewhere to get out. Personally I like to keep that 
statement
near the top of the loop if possible - just so that I can
find it easily!

So in your case I'd add a test like

if mo_hp >= 0:
    break

right at the top of the loop.

If there were other statements after the loop these would then
get executed but since you don't your program will naturally 
terminate.

Note that if you had an else clause in your while loop(quite unusual)
it does not get executed after a break - the only useful feature I've
found for a loop else condition!

ie

while True:
     break
else:  print 'never executed'
print 'exited'

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list