Python Tutorial‎ > ‎

Tutorial Six

While Loops
This tutorial is for the Python IDLE (GUI) - Graphical User Interface
Click the images to enlarge them

In the program we made in the last tutorial we had to re-run the program for every input, to make the program continue we need to add a loop.
The most simple loop in Python is arguably a while loop. While loops are conditional loops to an extent.  
Loops execute a section of code and then loop back to the beginning of that section. While loops continue to loop to the beginning of that section while a value is true, hence the name while loop, and why it is a conditional to an extent.
In practice while loops are used in nearly everything, here's an example:
while numberofguesses < 5
ask for guess, if guess = 2 then continue
else numberofguesses = numberofguesses + 1

We can also use a while loop to continue a program until a user chooses to exit. Here's an example:
continue = 1
while continue = 1
ask for two numbers to add
add the numbers and output them
ask the user if they want to exit, if they want to exit set continue = 0

In the program above continue will always = 1, therefor the program will continue to loop around, however when the user chooses to exit continue = 0 therefor the program will not loop to the beginning therefor ending the program.

Now we will edit our program from the previous tutorial, so now it will continue to ask for our guesses until we choose not to:

Loops program

number = 0
contin = 1
close = 0
while contin == 1:
    number = input("How many legs do humans have?")
    if number == "2":
        print ("Correct")
    else:
        print ("Incorrect")
    close = input ("Press 1 if you want to exit..")
    if close == "1":
        contin = 0


In this program we can continue to answer the question until we press 1 to exit.

Try for yourself to change the program to automatically end when you answer correctly.







Next tutorial - ?