Python while Loops


Python Loops

Python has two classic loop commands:

  • while loops
  • for loops

The While Loop

With a while loop we can make a set of statements as long as the situation is real.


Example

Print i as long as i is less than 6:

i = 1
while i < 6:
  print(i)
  i += 1

Note: remember to enlarge i, otherwise the loop will continue permanently.


The while loop requires a variable that is right for you, in this example we need to define the variable variable, i, that we have set to 1.


The break Statement

With a break statement we can stop the loop even if the timing is true:


Example

Exit the loop when i is 3:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1


The continue Statement

With an continue statement we can stop the current recurrence, and proceed with the following:


Example

Continue to the next iteration if i is 3:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)


The else Statement

In other words we can use the else code block once the situation is no longer true:


Example

Print a message once the condition is false:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")