Your First Steps in Python: A Beginner to Intermediate Guide

Loops: Repeating Actions

Section 4

Control Flow: Making Decisions and Repeating Actions

Your First Steps in Python: A Beginner to Intermediate GuideControl Flow: Making Decisions and Repeating Actions

So far, we've learned how to execute code line by line and how to make simple decisions using if statements. But what if you need to perform an action multiple times? This is where loops come in! Loops are fundamental to programming as they allow us to automate repetitive tasks, saving us a tremendous amount of time and effort.

Python offers two primary types of loops: the for loop and the while loop. Each has its own strengths and is suited for different scenarios.

The for loop is designed to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in that sequence. It's perfect when you know exactly how many times you want to repeat an action, or when you want to process each element of a collection.

The general syntax for a for loop looks like this:

for item in sequence:
    # Code to be executed for each item

Let's break this down:

  • for: This keyword initiates the loop.
  • item: This is a variable that will take on the value of each element in the sequence one by one during each iteration.
  • in: This keyword connects the item to the sequence.
  • sequence: This is the iterable object (like a list or a string) that the loop will go through.
  • The colon : marks the end of the for statement and the beginning of the indented code block that will be repeated.

Here's a simple example using a list of fruits:

チャプターへ戻る