Python

 

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 until counter exceeds 5. Each time the loop runs, counter is incremented by 1 using counter += 1.

How to Run the Program

To run the provided Python program:

  1. Open your Python editor or IDE (like PyCharm, Visual Studio Code, or even a simple text editor with Python support).
  2. Copy and paste the provided code into a new Python file (e.g., loops.py).
  3. 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.
  4. You should see the numbers 1 through 5 printed in the terminal or output window for both loops.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)