This cheat sheet python while Loop comes from the Python While Loop learning post. You can also check out Python.org for more information on while loops. Cheat Sheet Python While Loop is one of many cheat sheets that we are creating to help everyone out. It’s for those that always forget the small things(like me).
A while loop executes the body of the loop while the condition remains True.
Topics Covered
Syntax:
while condition:
body
Common mistakes:
Failure to initialize variables. Make sure all the variables used in the loop’s condition are initialized before the loop.
Unintended infinite loops. Make sure that the body of the loop modifies the variables used in the condition so that the loop will eventually end for all possible values of the variables.
Typical use:
While loops are mostly used when there’s an unknown number of operations to be performed, and a condition needs to be checked at each iteration.
Break & Continue
You can interrupt the while loop using the break keyword. We normally do this to interrupt a cycle due to a separate condition.
You can use the continue keyword to skip the current iteration and continue with the next one. This is typically used to jump ahead when some of the elements of the sequence aren’t relevant.