Loops in Python: for and while Explained | Python Tutorials | Python

Loops are used to repeat a block of code multiple times. Python supports two main types of loops: for loops and while loops. These loops help automate repetitive tasks, iterate through data, and build efficient programs.

1. for Loop

The for loop is used to iterate over sequences like lists, tuples, strings, or ranges.

for item in sequence:
    # do something with item

2. while Loop

The while loop continues running as long as a condition is True.

while condition:
    # do something

3. Loop Control Statements

  • break: Exit the loop immediately.
  • continue: Skip the current iteration and move to the next.
  • else: Executes after the loop finishes (if not broken early).

Example 1: Basic for Loop

for i in range(5):
    print("Iteration:", i)

Prints numbers from 0 to 4 using range().

Example 2: Iterating Over a List

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

Loops through each item in the list.

Example 3: while Loop Counter

count = 0

while count < 3:
    print("Count is", count)
    count += 1

Executes the block until the condition becomes false.

Example 4: break Statement

for i in range(10):
    if i == 5:
        break
    print(i)

Stops the loop when i becomes 5.

Example 5: continue Statement

for i in range(5):
    if i == 2:
        continue
    print(i)

Skips the value 2 and continues the loop.

Example 6: Using else with Loops

for i in range(3):
    print(i)
else:
    print("Loop finished")

The else block runs after the loop completes normally.

Example 7: Looping Over a String

for char in "Python":
    print(char)

Prints each character one by one.

Example 8: Reverse Countdown with while

num = 3

while num > 0:
    print(num)
    num -= 1

Counts down from 3 to 1.

Example 9: Nested Loops

for i in range(2):
    for j in range(2):
        print(i, j)

Nested loops are useful for matrix-like structures.

Example 10: Summing Numbers with a Loop

total = 0

for i in range(1, 6):
    total += i

print("Sum is", total)

Calculates the sum of numbers from 1 to 5.


Best Practices

  • Use for loops when iterating over a sequence or fixed number of times.
  • Use while loops when the end condition is dynamic or unknown.
  • Keep loops readable and avoid deep nesting unless necessary.
  • Use break and continue judiciously to control flow.

Loops are a core building block in Python. Once you master them, you’ll be able to build logic that handles everything from automation to data analysis and game logic.