Python For Loop


What is a for loop in Python and why is it used?

A for loop lets you run a piece of code again and again for each value in a sequence. Whenever you want to go through items one by one, a for loop becomes the easiest and cleanest solution. You do not track counters manually unless needed, and you do not write repeated print or calculation lines. Python handles the flow behind the scenes.

A for loop is used when:

  • You know how many items you want to process.

  • You want to handle each item of a list, string or tuple.

  • You want to repeat an action a fixed number of times.

  • You want to generate repeated results based on a pattern.

What is the basic syntax of a for loop?

The basic pattern is simple:

for variable in sequence:
    # code to run

Python checks each item in the sequence, stores it in the loop variable and executes the indented block. When there are no items left, the loop stops.

Example:

for name in ["Anita", "Riya", "Meera"]:
    print(name)

This structure stays the same regardless of the sequence type.

How does a for loop work with the range() function?

Most beginners use range() to run loops a specific number of times. The range() function generates numbers in a sequence. You can pass one, two or three arguments.

Basic usage:

for i in range(5):
    print(i)

This prints numbers 0 to 4.

Range with start and stop:

for i in range(1, 6):
    print(i)

Range with step:

for i in range(0, 20, 5):
    print(i)

The step value controls how the sequence moves forward. This is useful for loops that require patterns, such as working with only even numbers or jumping in intervals.

How do I loop through lists, strings and other sequences?

A for loop works naturally with any collection.

Looping through a list:

fruits = ["apple", "banana", "mango"]
for fruit in fruits:
    print(fruit)

Looping through a string:

for char in "Python":
    print(char)

Looping through a dictionary by keys:

info = {"name": "Asha", "age": 22}
for key in info:
    print(key)

Looping through dictionary items:

for key, value in info.items():
    print(key, value)

When you work with many beginner-friendly tasks like printing item names, filtering values or formatting data, these loops become your main tool.

How do I use for loops with conditions?

You can add conditions inside loops to skip or process certain values.

Example:

numbers = [2, 5, 7, 12, 18]
for n in numbers:
    if n % 2 == 0:
        print("Even:", n)

Another example with string filtering:

names = ["Anita", "Riya", "Aarti", "Meera"]
for n in names:
    if n.startswith("A"):
        print(n)

Conditions inside loops help you build search systems, filters and basic checks without writing long code.

How to use nested for loops?

A nested loop means one loop inside another. It is used when you want to process pairs, grids, combinations or multi-level data.

Example:

colors = ["red", "blue"]
sizes = ["S", "M", "L"]

for c in colors:
    for s in sizes:
        print(c, s)

Nested loops are useful in pattern printing, working with tables, generating combinations or handling list-of-lists.

How does break and continue work with for loops?

Sometimes you need to stop a loop early or skip an item.

Break example:

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

Continue example:

for x in range(10):
    if x % 2 == 0:
        continue
    print(x)

These tools control loop flow and give you flexibility when processing data.

How to use the else block with a for loop?

Python allows an optional else with a for loop. The else block runs only when the loop completes normally, without hitting a break.

Example:

for n in [2, 4, 6]:
    if n == 3:
        break
else:
    print("Number 3 not found")

This pattern helps build search tasks where you want a final confirmation.

Real-world example: calculating totals

prices = [120, 340, 220, 90]
total = 0

for p in prices:
    total += p

print("Total:", total)

This pattern appears often in billing systems, dashboards, reports and analytics.

Real-world example: counting characters

sentence = "Python loops are easy"
count = 0

for ch in sentence:
    if ch == "a":
        count += 1

print("Count of 'a':", count)

This introduces beginners to counting logic and string analysis.

Summary of the Tutorial

A for loop is one of the most important tools in Python programming. It simplifies repetition, helps you process lists and strings, makes range-based loops cleaner and supports conditions, nested loops and loop-control statements. Learn the patterns of iterating through collections, filtering values, using range, breaking and continuing loops, and you will be able to handle most beginner-level programming tasks smoothly.


Practice Questions

  1. Write a for loop that prints numbers from 1 to 20 using range().
  2. Create a list of five fruits and use a for loop to print each fruit in uppercase.
  3. Use a for loop to print all even numbers between 1 and 50.
  4. Write a program that asks the user for a word and prints each character on a new line.
  5. Create a loop that calculates the sum of all numbers from 1 to 100.
  6. Use nested loops to print all color–size combinations from two lists: ["red", "blue"] and ["S", "M", "L"].
  7. Write a for loop that searches a list for the value 37 and prints “Found” when it appears, using break.
  8. Use continue in a loop to skip all numbers divisible by 3 while printing numbers from 1 to 30.
  9. Write a loop that counts how many vowels are present in a given string.
  10. Given a list of prices, use a loop to calculate the total and print the final amount.

Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top