WHILE LOOP

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don’t know beforehand the number of times to iterate. This is useful when we want to allow the user to terminate the loop when they want to or perhaps even to keep looping until the user enters a valid entry.

While Loop Syntax

[python]
while expression_is_true:
statement(s)
[/python]

In a while loop, the condition is checked first. The body of the look will only execute if expression_is_true is actually true. After one iteration, it will check the condition again to see if it must execute the loop again. The body of the loop must be indented.

Let’s take a look at an example. The following program will continue to print a value as long as it is positive.

[python]
num = 10 #Here is our original value
while num>0: #This is the condition to check
print(num)
num-=1 #VERY IMPORTANT! You must update the variable before the next check

#Also, be sure that all lines that are to be executed are indented. Same as with the if statement.
[/python]

In this next example, we will prompt the user to enter in a value until they get the correct answer.

[python]
answer = input("What is the capital of Canada?: ") #Here we will allow the user to initialize the variable
while answer!="Ottawa":
print("Incorrect!")
answer = input("What is the capital of Canada?: ") #The user will now have a chance to update the variable once again.
[/python]

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the numbers and see if you can predict what the results will be.

The Infinte Loop

One of the major factors that you must remember when it comes to the while loop is that you MUST UPDATE THE VARIABLE BEFORE THE NEXT CONDITION CHECK. Notice how that’s all caps? It’s because it is that important.

Let’s take a look at what happens when you don’t.

[python]
verse = 1
while verse==1: #since verse is never updated, this will always be true
print("""\nThis is the song that never ends
Yes, it just goes on and on my friends.
Some people started singing it, not knowing what it was.
And they continue singing it forever just because,
This is the song that doesn’t end.""")
[/python]

This is known as an infinite loop. This will continue running forever until the user force closes the program as the variable is never updated.

Try executing this in the interpreter installed on your computer. Don’t run it on this website as bad things will happen.

Using the ‘Else’ Statement with a Loop

Python supports to have an else statement associated with a loop statement. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.

[python]
count = 0
while count==5:
print (count, "is less than 5")
count = count + 1
else:
print (count, "is not less than 5")
[/python]

Sample Code

Copy the code above and execute it. Does it create the result you expected? Change the numbers and see if you can predict what the results will be.

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material. Use the for loop and range function to complete the following:

  1. Create a program that repeatedly prints the value of the variable xValue, decreasing it by 0.5 each time, as long as xValue remains positive.
  2. Create a program that prints the square roots of the first 25 odd positive integers.
  3. Create a program that repeats a block of code as long as the user indicates they want it to.
  4. Create a program that will drive the user crazy by insisting they re-enter a particular input no matter what they enter. Be creative…