Introduction to The For Loop Journey

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.

Understanding the Concept of Loops

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!"

Introduction to For Loops in Python

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.

Riding through Python For Loops: Lists and Sets

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.

Riding through Python For Loops: Strings

Strings in Python are also iterable, meaning we can iterate over each character:

Riding through Python For Loops: Dictionaries

Finally, you can also iterate over dictionaries, traversing all its keys:

Exploring Applications of For Loops

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.

Lesson Summary

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal