Show Menu
Cheatography

Python While Loops Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Example

i = 1 
while i < 4:
 ­ ­ ­  print(i)
 ­ ­ ­  i += 1
>>> 1
>>> 2
>>> 3
With the
while
loop we can execute a set of statements as long as a condition is true. In this example the condition was that i must be less than 4.

The break Statement

i = 1 
while i < 4:
 ­ ­ ­  print(i)
 ­ ­ ­  if (i == 2):
        break
 ­ ­ ­  i += 1
>>> 1
With the
break
statement we can stop the loop even if the while condition is true. In this example the loop stopped when i is equal to 2.
 

The continue Statement

i = 1 
while i < 4:
 ­ ­ ­  print(i)
 ­ ­ ­  if (i == 2):
        continue
 ­ ­ ­  i += 1
>>> 1
>>> 3
With the
continue
statement we can stop the current iteration, and continue with the next. In this example the loop stopped when i is equal to 2 and continued the next iterat­ions.

The else Statement

i = 1 
while i < 4:
 ­ ­ ­  print(i)
 ­ ­ ­  i += 1
else:
 ­ ­ ­  print(­"i is no longer less than 4")
>>> 1
>>> 2
>>> 3
>>> i is no longer less than 4
With the
else
statement we can run a block of code once when the condition no longer is true.