Python Python Basics (2015) Number Game App Number Game Refinement

What is the purpose of an else: clause in a While block? Can't the code just be placed outside the While?

   While True: 
         #do stuff
   else:
      #continue with the program

Isn't this the same thing?

   While True: 
         #do stuff

#continue with the program
Alx Ki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alx Ki
Python Web Development Techdegree Graduate 14,810 Points

I guess Your code may (in some situation) get stuck to infinite loop and never ever get to the code below (if there is a need to get there). PS I may be wrong

1 Answer

If the statements in the else block were placed outside of the else block, they would run regardless of the while loop state.

If you had an action you wanted to perform based on the end state of the while loop, ie. as soon as the while loop was complete, put it in the else -- imagine the else as the end tag on the while.

Note that the else will only run when the while condition becomes false, and will not run if you exit the while loop with a break or return.

Oh cool. That now makes sense to me. If there were no else clause attached to the While loop a separate test would have to be programmed following the While block, perhaps testing some variable that was modified internally.

Thanks!