Python Loops

A loop is an instruction that executes code multiple times.


Python supports two loop types:

For both loop types, it’s possible to skip items in the loop or to break out of the loop. Each time we go through the loop is called an iteration.

For Loop

The for loop runs a defined amount of times before it ends. This is useful if you want to execute some code an X amount of times. You can also use the for loop to go through items in a sequence. For example, the items in a list.

While Loop

The while loop repeats itself over and over again and doesn’t end until a certain condition is met. Each time the loop ends, we check the condition again. When the condition is met, the loop ends. When the condition is not met, we execute the code in the loop again.

Conclusion

Loops are useful when you want to execute the same line(s) of code multiple times or when you want to process multiple items, for example, the items in a list. In the next two lessons, we’ll go through both loop types.


Ask a question or start a discussion by visiting our Community Forum