Topic Overview and Actualization

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.

Understanding Looping

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:

friends = ['Alice', 'Bob', 'Charlie', 'Daniel']
# `friend` is the loop variable, taking each name in the `friends` list
for friend in friends:
    # for each `friend`, this line is executed
    print(f"Hello, {friend}! Nice to meet you.")
"""
Prints:
Hello, Alice! Nice to meet you.
Hello, Bob! Nice to meet you.
Hello, Charlie! Nice to meet you.
Hello, Daniel! Nice to meet you.
"""

Loops allow us to automate repetitive sequences efficiently.

For Loop in Python

In Python, a for loop works with any sequence, like lists or strings. Let's print a range of numbers using a for loop:

# `num` runs through each number in the range of 5
for num in range(5):
    # This line will print numbers from 0 to 4
    print(num)

Each loop iteration updates the variable (num) to the next sequence value before executing the code block.

While Loop in Python

While loops execute code continuously until a condition becomes false. Here's a simple example:

num = 0
# The loop keeps running until num is greater than or equal to 5
while num < 5:
    print(num)
    # increase num by 1 each iteration
    num += 1

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.

Looping Over Collections

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:

# list of fruits
fruits = ['apple', 'banana', 'cherry']
# `fruit` stands for each fruit in the `fruits` list
for fruit in fruits:
    print(fruit) # prints each fruit

And, looping over a string:

word = 'hello'
# `letter` is each individual character in the `word`
for letter in word:
    print(letter) # prints each letter in 'hello'
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