While loops repeat as long as a certain boolean condition is met.
# remember to increment 'count', or else the loop will continue forever
count = 0
while count < 5:
print(count)
count += 1
The break Statement
The break
statement can stop the loop even if the while condition is true.
i = 1
while i < 10:
print(i)
if i == 3:
break
i += 1
The continue Statement
The continue
statement can stop the current iteration, and continue with the next.
i = 1
while i < 10:
i += 1
if i == 3:
continue
print(i)
The else Statement
The else
statement can run a block of code once when the condition no longer is true.
i = 1
while i < 5:
print(i)
i += 1
else:
print("i is no longer less than 5")
Exercise
Using the while loop, modify the code to print x as long as x is less than 9 but do not print the number 5.
x = 1
while x < 5:
print(x)
x += 1
x = 1
while x < 9:
if x == 5:
continue
print(x)
x += 1
test_object('x', incorrect_msg="Don't forget to read the instructions.")
test_output_contains("1")
test_output_contains("2")
test_output_contains("3")
test_output_contains("4")
test_output_contains("6")
test_output_contains("7")
test_output_contains("8")
test_output_contains("9")
success_msg("Excellent!")