Class 3 ‐ Loops - Justin-Boyd/Python-Class GitHub Wiki
For & While Loops
What Are Loops?
- Loops are blocks of code that run as long as a condition is true.
- They allow repeating code logic for as long as the condition is true.
For Loops

- Perform blocks of code if the condition is true
- A for loop provides iterating capabilities.
- Can iterate over lists, defined ranges, and more
Range vs. List in Loops

- List iteration allows printing data.
- A set range, defined by range(), is also capable of iteration.
- A variable is defined within the loop as the iterating item.
Calculate Loop Size

- The len() function returns the number of items of an object.
- The range() function accepts an integer and returns the range of the object.
While Loops

- Perform a block of code while a condition is true
- If the condition is false, the while loop will not be executed.
- While loops do not have iteration capability like for loops.
Break Command

- Both for and while loops can be interrupted.
- The break command exits a loop.
- Can be placed strategically for flow control
Continue Command

- Can be used in both for and while loops
- The continue command skips an iteration.
- Behaves as if the code reached the end of the block
Pass Command

- Pass statements are used as empty executions.
- This is useful for when we don't want to execute any code.
- Pass can be used as a placeholder for future code.
Pass vs. Continue

- Pass means move on to the remaining code or loop body.
- Continue forces the loop to begin the next iteration.
Loops & Conditions
Mixing Conditions and Loops

- Conditions have a major role in a loop’s flow control.
- They provide greater flexibility for loops.
- They also ensure more efficient conditional checks and help build a better code writing structure.
Infinite Loops

- A loop becomes infinite if a condition is never false.
- To avoid an infinite loop, the loop must verify the existence of a false condition.
Nested Loops and Lists

- The append() function can be used to define a list within another list.
- append() adds a value to an existing variable.
- Nested lists can be used to arrange data in hierarchical structures.