Python Tutorials

Python Programs

Python Loops


Python Loops

In this tutorial, we will learn about different types of loops in Python. We will cover the basics of for, while, and do-while loops.


What is a Loop

A loop is a control flow statement that allows code to be executed repeatedly based on a condition.

Loops

Python supports two types of loops: for loops and while loops. Although Python does not have a built-in do-while loop, it can be simulated using a while loop.

For Loop

A for loop is used when the number of iterations is known before entering the loop. The syntax for the for loop is:

for item in iterable:
    # Code block to be executed

While Loop

A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:

while condition:
    # Code block to be executed

Simulating Do-While Loop

Although Python does not have a built-in do-while loop, it can be simulated using a while loop with a break statement. The syntax for simulating a do-while loop is:

while True:
    # Code block to be executed
    if not condition:
        break


Printing Numbers from 1 to 10 using For Loop

  1. Declare a range from 1 to 10.
  2. Use a for loop to print numbers from 1 to 10.

Python Program

for i in range(1, 11):
    print(i, end=' ')

Output

1 2 3 4 5 6 7 8 9 10 


Printing Numbers from 1 to 5 using While Loop

  1. Declare an integer variable i and initialize it to 1.
  2. Use a while loop to print numbers from 1 to 5.

Python Program

i = 1
while i <= 5:
    print(i, end=' ')
    i += 1

Output

1 2 3 4 5 


Printing Numbers from 1 to 3 using Simulated Do-While Loop

  1. Declare an integer variable i and initialize it to 1.
  2. Use a while loop to simulate a do-while loop to print numbers from 1 to 3.

Python Program

i = 1
while True:
    print(i, end=' ')
    i += 1
    if i > 3:
        break

Output

1 2 3