Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,822 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!