While Loops

There are two types of loop in Python:

  • the for loop
  • the while loop

While loops are known as indefinite or conditional loops. They will keep iterating until certain conditions are met. There is no guarantee ahead of time regarding how many times the loop will iterate.

The while loop, like the if statement, includes a boolean expression that evaluates to true or false. The code inside the loop will be repeatedly executed until the boolean expression is no longer true.

This diagram shows the flow of control in a while loop:

While example

This video clip gives you some examples of writing while loops in Python.

WHILE Loop Examples

Here is an example of a while loop being used to test a password. The password is secret and the code within the loop is executed until the user inputs the correct password.

1
2
3
4
5
6
7
password = ""
while password != "secret":
    password = input("Please enter the password: ")
    if password == "secret":
        print("Thank you. You have entered the correct password")
    else:
        print("Sorry the value entered in incorrect - try again")

Here is another example showing a boolean variable being used to control the loop. This is very common with while loops. In this case, the boolean variable is named Invalid. Invalid is initially set to be True. The code within the loop is executed until Invalid is set to False. This is a good method for validating any input that needs to be within a certain range.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
invalid = True
while invalid:
    number = int(input("Please enter a number in the range 10 to 20: "))
    if number >= 10 and number <= 20:
        invalid = False
    else:
        print("Sorry number must be between 10 and 20")
        print("Please try again")
print("You entered {0}".format(number))
print("This is a valid number")