What are loops?
Loops let you repeat code without writing it multiple times. Instead of copying and pasting, you tell Python to repeat the code for you. Without loops:For loops
Thefor loop is the most common loop in Python. Let’s start simple:
Repeat a specific number of times
Python starts counting at 0, not 1. This is called “zero-indexing”. So
range(5) gives you 0, 1, 2, 3, 4 (five numbers total).Count from different starting points
Loop through text
You can loop through each character in a string:Loop through a list (preview)
We’ll learn more about lists later, but here’s a preview:While loops
Awhile loop continues as long as a condition is true:
Always make sure your while loop will eventually stop! If you forget to update the variable, it will run forever.
Common mistakes
Forgetting the colon
Forgetting the colon
Wrong indentation
Wrong indentation
Off-by-one errors
Off-by-one errors
Data structures
Learn about lists, dictionaries, and more