Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#18: Conditional Loops with while

                          << Previous Tutorial           Next Tutorial >>
On this page: <, while loop, terminating a loop, interrupting a process with Ctrl + C, -=.

Get Started

Video Summary

  • The first unsuccessful script and its output here. The error was fixed in this next version, producing this output.
  • This tutorial explains how to make a simple while loop, which is based on a conditional statement. As such, the while function used in this tutorial compares the size of two variables defined as different number values: myAge which is defined as 26 and DEATH which is defined as 69. These variables are arranged in the loop while myAge < DEATH:.
  • In this scenario, you can instruct Python to perform a series of commands which will continue to be executed until the statement within the loop is no longer valid. However, it is important to remember if no command is given to Python that will invalidate your statement, Python will continue looping endlessly until manually told to stop with the keyboard command CTRL + C. For example, The phrase while myAge < DEATH: will never terminate unless another command is inserted to alter the value of myAge or DEATH. As such, the print commands given within the while myAge < DEATH: loop in the tutorial repeat endlessly.
  • This is remedied within the tutorial by giving a final command within the while myAge < DEATH: loop to increase the value of myAge by 1. As a while loop repeats its commands until its conditional statement is invalid, myAge will increase in value until it is equal to DEATH, at which point the loop terminates.

Learn More

  • That CTRL + C is a very handy command: it interrupts any unwanted process, which occurs frequently when learning (and beyond). You should know it by heart.
  • You can also count down. Below is a New Year's count down script (courtesy of Elliot Halpern):
    countdown = 10
    newYear = 0
    
    while countdown > newYear:
        print countdown
        countdown -= 1
    
    print 'Happy New Year!'
    countdown.py 
    
  • Anne Dawson has many script examples for while. Search for "while" on the page and you will get over 20.

Explore