Hello, Explorer! Today, we will revisit Python loops, essential tools that simplify repetitive tasks. Think of loops like a marathon of TV series episodes. We will venture into the Python looping universe and acquire hands-on experience by applying loops to collections like lists and strings.
Have you ever experienced repeating a favorite song on a loop? That's what loops are all about in programming, too. For example, you can print greetings for a list of friends using a For loop:
Loops allow us to automate repetitive sequences efficiently.
In Python, a for loop works with any sequence, like lists or strings. Let's print a range of numbers using a for loop:
Each loop iteration updates the variable (num) to the next sequence value before executing the code block.
While loops execute code continuously until a condition becomes false. Here's a simple example:
As you can see, before each iteration, Python checks the condition (num < 5). If it's true, the code block runs; otherwise, Python exits the loop.
Python loops can directly work with collections, making it easy to handle elements of a list or string.
For instance, consider looping over a list:
And, looping over a string:
