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:

for variable in iterable_object:
    # executable code

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:

# List of planets
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

# Print each planet
for planet in planets:
  print(planet)
"""
Prints:
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
""" 

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:

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Print each number
for num in numbers:
  print(num)
"""
Prints:
1
2
3
4
5
"""

The same works for sets:

# Set of numbers
numbers = {1, 2, 5, 4, 3}

# Prints each number in the set
for num in numbers:
  print(num)
"""
Prints:
1
2
3
4
5
"""

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:

# A string
word = "Python"

# Print each character
for letter in word:
  print(letter)
"""
Prints:
P
y
t
h
o
n
"""
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