Repeat Yourself
Explore how to use Python's for and while loops to automate repetitive tasks. Learn to write cleaner, more efficient code by repeating actions a set number of times or until a condition changes.
We'll cover the following...
What if we wanted to plant 10 trees, send 5 reminders, or greet each student in a list without copying the same line of code repeatedly?
Instead of repeating the same line repeatedly, Python lets us loop through actions with just a few lines!
The for loops: Do it a set number of times
A for loop lets us repeat actions several times, saving time and keeping our code clean and powerful. It is perfect for knowing how many times we want something to run.
Try this:
In this example, Python repeats the line five times.
Note: In
for i in range(5):, the colon (:) tells Python, “I'm about to give you instructions to repeat.” The indented line below it (print("Hello!")) is what gets repeated.
The keyword in in a loop is used to iterate through elements of a list, string, or any iterable.
What’s range(5)?
range(5)gives Python the numbers 0, 1, 2, 3, 4.The loop runs once for each number in the range.
iis the loop variable, and it changes each time.
Try this:
The while loops: Repeat until done
Sometimes, we don’t know how many times to repeat something—we just want to keep going until a condition is no longer true.
That’s where a while loop comes in. It repeats a block of code as long as a condition stays true.
Try this:
Just like with if and for, a while loop needs a colon (:) to start the block. And the indented code under it is what gets repeated again and again, until the condition becomes False.
Good job! You’ve learned how to use loops to repeat actions and write cleaner code. Keep it up!