Python Loops

Loops in Python: Streamlining Repetition with Precision and Control.

Apr 12, 2026

Loops in Python


To execute a block of statements repeatedly for a finite number of times or until some condition is satisfied then repetition structures are used. The repetition structures are also known as loops, which repeat an action. Each repetition of the action is known as a pass or an iteration. There are two types of loops:
  • That repeat an action a predefined number of times (definite iteration)
  • That performs the action until it needs to stop (indefinite iteration).

The two loop statements in python are for and while.


For Loop

In Python, for loop is used for sequential traversal i.e. it is used for iterating over an iterable like String, Tuple, List, Set or Dictionary. The for loop which is similar to each loop in other languages. In Python, for loops only implement the collection-based iteration. The syntax of for loop in Python is:

for var in iterable:
    # statements

Here the iterable is a collection of objects like lists, tuples. The indented statements inside the for loops are executed once for each item in an iterable. The variable var takes the value of the next item of the iterable each time through the loop.

Example:

# sum of all items in the list
s = 0
for x in [1, 2, 3, 4, 5]:
    s = s + x
print("The sum of all items in the list is:", s)

Output:

The sum of all items in the list is: 15

The range() function is useful for creating a list. The general form of the range() function is range(number).

  • If range(10) — It takes all the values from 0 to 9.
  • If range(start, stop, interval_size) i.e. If range(2, 10, 2) — It lists all the numbers such as 2, 4, 6, 8.
  • If range(start, stop) i.e. range(1, 6) — lists all the numbers from 1 to 5, but not 6. Here, by default the interval size is 1.

Example:

# for loop to print the numbers 8, 11, 14, 17, 20, . . ., 83, 86, 89
for i in range(8, 90, 3):
    print(i, end=" ")

Output:

8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89

While Loop

While loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. The syntax of while loop is:

while expression:
    statement(s)

While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn't specified explicitly in advance. When a while loop is executed, expr is first evaluated in a boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then the body is executed again and this continues until the expression becomes false.

Example:

# Sum of given numbers
data = input('Enter any number')
sum = 0
while data != " ":
    sum = sum + int(data)
    data = input('Enter a number for sum and space for quit ')
print('The sum is:', sum)

Output:

Enter any number2
Enter a number for sum and space for quit 3
Enter a number for sum and space for quit
The sum is: 5

Count Control with While Loop

We can also use a while loop for count-controlled loops. The body of the while is repeatedly executed until the condition which returns a True. Otherwise the body of the loop is terminated and the first statement after the while loop will be executed.

Example:

# print the name any number of times
n = int(input('Enter the number of times to display your name: '))
name = input('Enter name: ')
while n > 0:
    print(name)
    n = n - 1
print('End of the program')

Output:

Enter the number of times to display your name: 3
Enter name: Libed
Libed
Libed
Libed
 
End of the program

Input Validation Loops

Loops can be used to validate user input. For instance, a program may require the user to enter a positive integer. Many of us have seen a "yes/no" prompt at some point, although probably in the form of a dialog box with buttons rather than text.

Example:

import random
action = "Y"
while action == "Y":
    print("Generating random number...")
    randomNumber = random.randint(1, 10)
    print("Random number is", randomNumber)
    action = input("Another(Y/N)?")
    while (action != "Y" and action != "N"):
        action = input("Invalid input! Enter Y or N:")
print("All done!")

Output:

Generating random number...
Random number is 2
Another(Y/N)?Y
Generating random number...
Random number is 10
Another(Y/N)?K
Invalid input! Enter Y or N:N
All done!

Nested Loops

Writing a loop statement inside another is called Nested loops. The inner loop will be executed one time for each iteration of the outer loop. Any type of loop can be an inner loop and outer loop. For example, a for loop can be an inner loop a while loop can be an outer loop or vice versa.

for var in iterable:        # outer for loop
    for var in iterable:    # inner for loop
        # statements
    # statements

Example:

for i in range(4):
    j = 0
    while j < (i + 1):
        print('*', end=' ')
        j = j + 1
    print('\n')

Output:

*
 
* *
 
* * *
 
* * * *

Else with Loops

In most programming languages the use of else statements has been restricted with the if conditional statements. Python allows us to use the else condition with for and while loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

Example:

# Demonstrate for-else loop
for i in range(1, 4):
    print(i)
else:  # Executed because no break in for
    print("No Break\n")

Output:

1
2
3
No Break

Jump Statements

We have three jump statements. Those are break, continue and pass.


Break Statement

The break statement brings control out of the loop. break statement terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C. The break statement can be used in both while and for loops.

Example:

for letter in 'LIBED':
    # break the loop as soon it sees 'B' or 'E'
    if letter == 'B' or letter == 'E':
        break
print('Current Letter :', letter)

Output:

Current Letter : B

Continue Statement

Python continue statement returns the control to the beginning of the loop. The continue statement skips all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

Example:

# Prints all letters except 'B' and 'E'
for letter in 'LIBED':
    if letter == 'B' or letter == 'E':
        continue
    print('Current Letter :', letter)

Output:

Current Letter : L
Current Letter : I
Current Letter : D

Pass Statement

The pass statement to write empty loops. pass is also used for empty control statements, functions, and classes. The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

Example:

# An empty loop
for letter in 'LIBED':
    pass
print('Last Letter :', letter)

Output:

Last Letter : D