[Tutor] Exiting a while

Alan Gauld alan.gauld at btinternet.com
Sat Jul 6 10:25:39 CEST 2013


On 06/07/13 04:33, Jack Little wrote:
> How would I exit a while statement. The while is to keep the player in
> combat with an enemy until said enemy is dead. I tried using an if, but
> it just doesn't work.

In most cases you make the while condition false.

while enemy.state != dead:
    # your loop code here

will automatically break when your enemy state is dead.

Another common idiom is to use an infinite loop:

while True:   #loops forever
    if enemy.state == dead:
       break   # exits the nearest containing loop
    # your loop code here

The first form is better since it requires less maintenance
but had the disadvantage that you often have to initialize
the condition prior to the loop which can lead to repeated
code - another maintenance headache. You have to choose.

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



More information about the Tutor mailing list