Welcome! In programming, just like playing a favorite song on repeat, loops execute code repeatedly. Here, we'll explore the "For Loop" in Python, an iteration construct over sequences such as lists or strings.
Imagine a train journey: the train represents our loop, stopping at each station. Each station represents an item on its route, which is the iterable
.
Like replaying a song or game level, a loop continually executes a block of code until a defined condition is met. It's akin to saying, "Keep the popcorn machine running as long as the popcorn keeps popping!"
A Python For Loop looks like this:
In this construct, for
and in
are keywords. The variable
holds the current item in each iteration, while iterable_object
can be a list, string, or any object that provides an item sequentially.
Let's print all elements of a list:
This code will print every planet from the list (Mercury
, Venus
, Earth
, ...), each on a separate line.
Let's delve further into For Loops by printing each number from a list:
The same works for sets:
Note that because sets are unordered, results might appear in any order.
Strings in Python are also iterable
, meaning we can iterate over each character:
Finally, you can also iterate over dictionaries, traversing all its keys:
Loops are powerful tools for repetitive tasks, like adding all numbers in a list:
The For Loop here adds all items in the list using concise, comprehensible code.
Excellent! You've learned about For Loops and observed how they can automate repetitive tasks and simplify code. Real-life examples, such as aggregating numbers in a list and printing string characters, were demonstrated. Now, it's time to reinforce what you've learned with practice. Both learning and practicing are crucial to mastering these concepts and enhancing your skills. We look forward to our next lesson on While Loops. See you there!
