Skip to content

While Loops

While Loops

A While Loop is a type of loop that will continues running as long as an assigned logical condition is True. When the logical condition returns False, the loop will stop running. The general form of a while loop is below:

while logical_condition:
    code

The keyword while must be included, as well as a logical_condition that can be evaluated as True or False. The code after the while statement must be indented and each line of code that runs as part of the loop needs to be indented the same number of spaces. An example is below:

In [1]:
print('Engineers solve problems in teams')
print('Engineers solve problems in teams')
print('Engineers solve problems in teams')

Engineers solve problems in teams
Engineers solve problems in teams
Engineers solve problems in teams

In the previous code section, the first line i=0 created a variable i and assigned it the value 0. The second line declared a while loop using the keyword while and the logical condition i<4. The logical condition i<4 will be True or False depending on the variable i. Since i=0, the logical condition i<4 is True and the for loop starts to run. The code that run inside the loop prints the value of i then increases i by 1. Eventually, when i=4, the statement i<4 is False and the while loop ends.

Using a while loop to validate user input

While loops can be utilized to validate user input. Say we want to insist a user inputs a positive number. This can be accomplished using a while loop that keeps on repeating until the user enters valid input. The code below will continue to ask a user for a positive number until one is entered.

In [2]:
num_input = -1
while num_input < 0:
    str_input = input('Enter a positive number: ')
    num_input = float(str_input)

Enter a positive number: -1
Enter a positive number: -3
Enter a positive number: 4

In the section of code above, it is important to initialize the variable num_input with a value that causes the while statement num_input < 0 to evaluate as True. num_input = -1 causes the statement num_input < 0 to evaluate as True and any other negative number would have worked as well. If the while statement can't be evaluated as True or False, Python will throw an error. It is therefore necessary to convert the user's input from a string to a float. The statement '4' < 0 does note evaluate to True or False, because the string '5' can't be compared to the number 0.