Introduction
In Python, loops are used to iterate over a sequence (like a list, tuple, or string) or execute a block of code repeatedly. The two main types of loops in Python are the for loop and the while loop. Understanding how to use these loops is crucial for controlling the flow of your program and handling repetitive tasks efficiently.
Objective
In this tutorial, you will learn the following:
- How to use a for loop to iterate over a sequence of items.
- How to use a while loop to repeat a block of code until a condition is met.
- How to control loop execution with break, continue, and else statements.
Code Examples
For Loop Example
# For loop to iterate through a list of numbers numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
While Loop Example
# While loop to print numbers from 1 to 5 counter = 1 while counter <= 5: print(counter) counter += 1
Program Explanation
The two loops serve different purposes:
- For Loop: The for loop iterates over each item in a sequence (in this case, a list of numbers). The loop starts by assigning the first item in the list to the variable
number
and executes the indented block of code. This continues until all items in the list have been processed. - While Loop: The while loop continues to execute the indented block of code as long as the given condition is true. In this example, it prints the value of
counter
untilcounter
exceeds 5. Each time the loop runs,counter
is incremented by 1 usingcounter += 1
.
How to Run the Program
To run the provided Python program:
- Open your Python editor or IDE (like PyCharm, Visual Studio Code, or even a simple text editor with Python support).
- Copy and paste the provided code into a new Python file (e.g.,
loops.py
). - Save the file and run it using the Python interpreter by typing
python loops.py
in the command line or running the file directly from your IDE. - You should see the numbers 1 through 5 printed in the terminal or output window for both loops.