Python Loops
Python gives you two basic kinds of loop:
whileloopsforloops
The while Loop
A while loop keeps running its statements for as long as its condition stays true.
Note: Don't forget to increase i. If you leave that out, the loop never ends.
Any variables the while loop depends on must exist before it starts. Here that means an indexing variable, i, with a starting value of 1.
Example
Keep printing i while it is below 6:
Output: complete Python program
i = 1
while i < 6:
print(i)
i += 1
The break Statement
A break statement ends the loop right away, even though the while condition is still true:
Example
Leave the loop as soon as i is 3:
Output: complete Python program
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
A continue statement abandons the current iteration and moves on to the next one:
Example
Skip printing when i is 3 and move on:
Output: complete Python program
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
An else statement gives the loop a block of code that runs one time, at the moment the condition stops being true.
Note: A loop that ends through a break statement does NOT run its else block.
Example
Print a message when the condition turns false:
Output: complete Python program
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")