While loop

Courses

While loops
Sometimes we are not sure how long sometimes will take. For example, how long a car driver would be adding petrol. A program could be (pseudocode):

while petrol_filling:
   increase price
   show price
   add petrol

Python has the while keyword.  Lets build an extended ‘guess the number game’:

x = 0
while x != 5:
   x = int(input("Guess a number:"))
   
   if x != 5:
      print("Incorrect choice")

print("Correct")

This will keep asking a number until the number is guessed.   This is defined in the line: while x != 5, or in English,  “while x is not equal to five, execute”.

Illustrated:
while-loop
The program keeps repeating the code block while the condition (x!=5) is True. Once x equals 5, the program continues.

Infinite loops
If a condition in a while loop is never met, it could cause the program to run forever or to freeze/crash.

For loops
Functions

2 thoughts on “While loop

  1. Reply
    bob wolff - May 10, 2017

    Ok…..I give…..what terminates the WHILE LOOP? I’m not asking when the loop condition changes, what terminates the code contained in the WHILE loop? Is it simply formatting? (TAB positions)

    1. Reply
      admin - May 15, 2017

      Without the condition being true, it will continue forever (or until memory overflow). The break keyword can make it stop as well. In most of the cases, you want to be sure the while loop condition is met. Some while loops should last forever except if the machine is turned of, like a web server or computer game.

Leave a Reply

Your email address will not be published. Required fields are marked *