Paramclasses Academy - Blog

Tutorials Details

←
Post 6 of 20
→

Python for Loop: Syntax, range(), Lists, Strings & Examples

Python for Loop: Syntax, range(), Lists, Strings & Examples

October 17, 2026

PYTHON FOR LOOP: SYNTAX, RANGE(), LISTS, STRINGS & EXAMPLES

1. WHAT IS A FOR LOOP IN PYTHON?

A for loop in Python is used to execute a block of code repeatedly for each item in a sequence or iterable.

Instead of writing the same statement multiple times, you can use a for loop to process multiple values with fewer lines of code.

Examples of where for loops are used:

  1. Printing numbers from 1 to 100.

  2. Displaying student names from a list.

  3. Calculating the total price of products.

  4. Processing customer records.

  5. Iterating through characters in a string.

  6. Generating reports and summaries.

  7. Processing data from files and databases.

Example:

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

Output:

1
2
3
4
5

Explanation:

The loop executes five times and displays numbers from 1 to 5.


2. WHAT IS THE SYNTAX OF A PYTHON FOR LOOP?

The syntax defines how a for loop is written in Python.

Syntax:

for variable in iterable:
    # Code to execute

Explanation:

  • for: Starts the loop.

  • variable: Stores the current item during each iteration.

  • in: Connects the variable to the iterable.

  • iterable: An object that provides items one at a time, such as a list, string, tuple, or range.

  • Colon (:): Marks the beginning of the loop body.

  • Indentation: Identifies the statements that belong to the loop.

Example:

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)

Output:

Apple
Banana
Mango

Explanation:

The loop processes each fruit in the list and prints its name.


3. HOW DOES A FOR LOOP WORK?

A for loop takes one item at a time from an iterable and executes the indented statements for that item.

Example:

for number in [10, 20, 30]:
    print(number)

Output:

10
20
30

Step-by-step execution:

  1. The first iteration assigns 10 to number.

  2. The second iteration assigns 20 to number.

  3. The third iteration assigns 30 to number.

  4. When there are no more items, the loop finishes.

Important: A for loop does not always need a numeric counter. It can iterate directly over the items of a list, string, tuple, and other iterable objects.


4. USING range() WITH A FOR LOOP

The range() function generates a sequence of integers. It is commonly used when you want to repeat an operation a specific number of times.

A. range(stop)

Example:

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

Output:

0
1
2
3
4

Explanation: range(5) generates numbers from 0 to 4. The stop value, 5, is excluded.

B. range(start, stop)

Example:

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

Output:

1
2
3
4
5

Explanation: The sequence starts at 1 and stops before 6.

C. range(start, stop, step)

The step argument determines the difference between consecutive numbers.

Example:

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

Output:

2
4
6
8
10

Explanation: The loop increases the value by 2 during each iteration.

D. Print Numbers in Reverse Order

Example:

for i in range(5, 0, -1):
    print(i)

Output:

5
4
3
2
1

Explanation: A negative step allows the sequence to move backward.


5. ITERATING THROUGH A LIST USING A FOR LOOP

A list stores multiple items in a single variable. A for loop can access every item without manually using indexes.

Example:

students = ["Rahul", "Amit", "Priya", "Neha"]

for student in students:
    print(student)

Output:

Rahul
Amit
Priya
Neha

Explanation: Each student name is assigned to the student variable in turn.

Real-Time Example: Display Product Names

products = ["Laptop", "Keyboard", "Mouse", "Monitor"]

for product in products:
    print("Product:", product)

Output:

Product: Laptop
Product: Keyboard
Product: Mouse
Product: Monitor

Real-time application: Online shopping websites can use similar iteration logic to process or display collections of products.


6. ITERATING THROUGH A STRING USING A FOR LOOP

A string is a sequence of characters. A for loop can process one character at a time.

Example:

language = "Python"

for character in language:
    print(character)

Output:

P
y
t
h
o
n

Explanation: The loop reads each character in the string and prints it on a separate line.

Real-Time Example: Count Characters

name = "Rahul"
count = 0

for character in name:
    count += 1

print("Total characters:", count)

Output:

Total characters: 5

Note: For a simple string, Python's built-in len() function is more direct. This example demonstrates how a loop can count characters manually.


7. USING A FOR LOOP WITH TUPLES

A tuple is an ordered collection that cannot be modified after creation.

Example:

colors = ("Red", "Green", "Blue")

for color in colors:
    print(color)

Output:

Red
Green
Blue

Explanation: The loop visits each tuple item in order.

Common uses: Reading fixed collections of values, processing coordinates, and iterating over grouped data.


8. USING A FOR LOOP WITH DICTIONARIES

A dictionary stores data as key-value pairs.

A. Iterate Through Dictionary Keys

student = {
    "name": "Rahul",
    "age": 20,
    "city": "Raipur"
}

for key in student:
    print(key)

Output:

name
age
city

B. Iterate Through Dictionary Values

for value in student.values():
    print(value)

Output:

Rahul
20
Raipur

C. Iterate Through Keys and Values

for key, value in student.items():
    print(f"{key}: {value}")

Output:

name: Rahul
age: 20
city: Raipur

Explanation: The items() method provides each key-value pair, which can be unpacked into two variables.


9. USING A FOR LOOP WITH CONDITIONS

A for loop can be combined with an if statement to process only items that satisfy a condition.

Example: Print Even Numbers

for number in range(1, 11):
    if number % 2 == 0:
        print(number)

Output:

2
4
6
8
10

Explanation: The modulo operator % returns the remainder. An even number has a remainder of zero when divided by 2.

Example: Find Positive Numbers

numbers = [10, -5, 20, -2, 0, 15]

for number in numbers:
    if number > 0:
        print(number)

Output:

10
20
15

Real-time application: Conditions inside loops help filter records, identify eligible items, and process data according to business rules.


10. CALCULATE THE SUM OF NUMBERS USING A FOR LOOP

A loop can maintain a running total by adding each number to an accumulator variable.

Example:

total = 0

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

print("Total:", total)

Output:

Total: 15

Explanation:

  • Initially, total is 0.

  • The loop adds 1, then 2, then 3, then 4, and finally 5.

  • The final total is 15.

Real-Time Example: Calculate Shopping Total

prices = [100, 250, 150, 200]
total = 0

for price in prices:
    total += price

print("Total Bill: Rs.", total)

Output:

Total Bill: Rs. 700

Real-time application: Similar logic can be used to calculate subtotals from a collection of product prices.


11. FIND THE LARGEST NUMBER USING A FOR LOOP

A for loop can compare values to find the largest number in a collection.

Example:

numbers = [12, 45, 7, 89, 34]

largest = numbers[0]

for number in numbers:
    if number > largest:
        largest = number

print("Largest number:", largest)

Output:

Largest number: 89

Explanation: The program starts with the first item as the largest value. Each subsequent item is compared with it, and the value is updated when a larger number is found.

Note: This example assumes the list is not empty. Python also provides the built-in max() function for finding the largest item directly.


12. NESTED FOR LOOPS IN PYTHON

A nested for loop is a for loop placed inside another for loop.

The inner loop runs completely for each iteration of the outer loop.

Syntax:

for outer_variable in outer_iterable:
    for inner_variable in inner_iterable:
        # Code to execute

Example: Display a Number Pattern

for i in range(1, 4):
    for j in range(1, 4):
        print(j, end=" ")
    print()

Output:

1 2 3
1 2 3
1 2 3

Explanation:

  • The outer loop runs three times.

  • For each outer iteration, the inner loop prints 1, 2, and 3.

  • The final print() moves the output to a new line.

Real-Time Uses of Nested Loops

  1. Processing rows and columns in a table.

  2. Generating patterns.

  3. Working with two-dimensional lists.

  4. Comparing items from two collections.

  5. Processing matrix data.

Important: Nested loops can increase execution time when both loops process large collections.


13. USING break AND continue WITH A FOR LOOP

The break and continue statements control loop execution.

A. break Statement

The break statement terminates the loop immediately.

Example:

for number in range(1, 10):
    if number == 5:
        break
    print(number)

Output:

1
2
3
4

Explanation: When the number becomes 5, the loop stops completely.

B. continue Statement

The continue statement skips the current iteration and proceeds to the next one.

Example:

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

Output:

1
2
4
5

Explanation: The number 3 is skipped, but the loop continues with 4 and 5.

Key difference:

  • break: Stops the loop.

  • continue: Skips only the current iteration.


14. USING enumerate() WITH A FOR LOOP

The enumerate() function allows you to access both the index and the item during iteration.

Example:

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 Apple
1 Banana
2 Mango

Start Indexing From 1

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

Output:

1 Apple
2 Banana
3 Mango

Real-time application: Use enumerate() when displaying numbered lists, ranking items, or showing row numbers in reports.


15. REAL-TIME PROJECT: STUDENT MARKS REPORT

Scenario: A teacher wants to display each student's marks and calculate the total marks.

Program:

students = [
    {"name": "Rahul", "marks": 85},
    {"name": "Amit", "marks": 78},
    {"name": "Priya", "marks": 92}
]

total_marks = 0

for student in students:
    print(
        f"Student: {student['name']}, "
        f"Marks: {student['marks']}"
    )
    total_marks += student["marks"]

print("Total Marks:", total_marks)
print("Number of Students:", len(students))

Output:

Student: Rahul, Marks: 85
Student: Amit, Marks: 78
Student: Priya, Marks: 92
Total Marks: 255
Number of Students: 3

Concepts used:

  • For loops

  • Lists

  • Dictionaries

  • Dictionary access

  • Variables

  • Arithmetic operations

  • f-strings

Real-time application: This structure can be extended to calculate average marks, identify the highest scorer, and generate student reports.


16. REAL-TIME PROJECT: PRODUCT BILL CALCULATOR

Scenario: A shop needs to calculate the total value of multiple products.

Program:

products = [
    {"name": "Notebook", "price": 50, "quantity": 4},
    {"name": "Pen", "price": 10, "quantity": 5},
    {"name": "Bag", "price": 500, "quantity": 1}
]

grand_total = 0

for product in products:
    subtotal = product["price"] * product["quantity"]
    grand_total += subtotal

    print(f"Product: {product['name']}")
    print(f"Subtotal: Rs. {subtotal:.2f}")
    print("--------------------")

print(f"Grand Total: Rs. {grand_total:.2f}")

Output:

Product: Notebook
Subtotal: Rs. 200.00
--------------------
Product: Pen
Subtotal: Rs. 50.00
--------------------
Product: Bag
Subtotal: Rs. 500.00
--------------------
Grand Total: Rs. 750.00

Explanation: The loop calculates the subtotal for each product and adds it to the grand total.

Real-time application: This concept is useful in billing systems, inventory software, and shopping applications.


17. COMMON MISTAKES WHEN USING FOR LOOPS

Mistake 1: Incorrect Indentation

Incorrect:

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

This produces an IndentationError.

Correct:

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

Mistake 2: Misunderstanding range()

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

Output:

1
2
3
4

The stop value 5 is not included.

Mistake 3: Forgetting That Strings Are Iterables

for letter in "Cat":
    print(letter)

The loop prints each character, not the complete word on every iteration.

Mistake 4: Using an Empty Range

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

This loop does not execute because the default step is positive and the start is greater than the stop.

Correct reverse range:

for i in range(5, 1, -1):
    print(i)

Output:

5
4
3
2

Mistake 5: Modifying a List While Iterating Over It

Removing elements from a list while looping over the same list can cause elements to be skipped.

Better approach:

numbers = [1, 2, 3, 4, 5]

filtered_numbers = [
    number for number in numbers
    if number % 2 == 0
]

print(filtered_numbers)

Output:

[2, 4]

This creates a new list containing only even numbers.


18. PRACTICE PROGRAMS

Write the following programs independently using Python for loops.

Program 1: Print Numbers

Print numbers from 1 to 100.

Program 2: Even Numbers

Display all even numbers between 1 and 50.

Program 3: Odd Numbers

Display all odd numbers between 1 and 50.

Program 4: Multiplication Table

Accept a number and print its multiplication table from 1 to 10.

Program 5: Sum of Natural Numbers

Calculate the sum of numbers from 1 to n.

Program 6: Factorial Calculator

Calculate the factorial of a non-negative integer using a loop.

Program 7: List Total

Calculate the total of all numbers in a list.

Program 8: Largest Number

Find the largest value in a list without using max().

Program 9: Count Vowels

Count the vowels in a string using a for loop.

Program 10: Reverse Number Sequence

Print numbers from 20 down to 1.

Program 11: Student Report

Display student names and marks from a list of dictionaries.

Program 12: Shopping Bill

Calculate individual product subtotals and the final bill.

Program 13: Star Pattern

Print a right-angled triangle using nested for loops.

Program 14: Search a Value

Search for a given number in a list and stop when it is found using break.

Program 15: Filter Numbers

Print only positive numbers from a list using a loop and an if statement.


19. PYTHON FOR LOOP QUIZ

Q1. What is the main purpose of a for loop in Python?

A. To define a class
B. To iterate over items in an iterable
C. To create a database

Answer: B. To iterate over items in an iterable.

Q2. What is the output of range(5) when used in a loop?

A. 1, 2, 3, 4, 5
B. 0, 1, 2, 3, 4
C. 0, 1, 2, 3, 4, 5

Answer: B. 0, 1, 2, 3, 4.

Q3. Which symbol is required after a for loop statement?

A. Semicolon
B. Colon
C. Comma

Answer: B. Colon.

Q4. Which statement stops a loop immediately?

A. continue
B. break
C. pass

Answer: B. break.

Q5. Which statement skips the current iteration?

A. break
B. continue
C. return

Answer: B. continue.

Q6. Which function provides both an index and an item during iteration?

A. enumerate()
B. input()
C. type()

Answer: A. enumerate().

Q7. What is the output?

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

Answer:

2
3
4

Q8. Can a for loop iterate through a string?

A. Yes
B. No

Answer: A. Yes.

Q9. What does range(1, 10, 2) generate?

A. 1, 3, 5, 7, 9
B. 1, 2, 3, 4, 5, 6, 7, 8, 9
C. 2, 4, 6, 8, 10

Answer: A. 1, 3, 5, 7, 9.

Q10. What is a nested for loop?

A. A loop inside another loop
B. A function inside a class
C. A loop without a condition

Answer: A. A loop inside another loop.


20. MODULE 6 — PART 17 ASSIGNMENT

Complete these tasks to strengthen your understanding of for loops.

  1. Print numbers from 1 to 100.

  2. Print even numbers from 1 to 100.

  3. Print the multiplication table of any number.

  4. Calculate the sum of natural numbers.

  5. Find the factorial of a number.

  6. Count vowels in a string.

  7. Find the largest number in a list.

  8. Display dictionary keys and values.

  9. Build a student marks report.

  10. Build a product billing calculator.

  11. Print a star pattern using nested loops.

  12. Use break to stop a loop when a target value is found.

  13. Use continue to skip multiples of 3.

  14. Use enumerate() to display a numbered list.

  15. Filter positive and negative numbers from a list.

Assignment goal: Write, run, and test each program. Check the output and correct any errors before moving to the next topic.


21. SUMMARY: PYTHON FOR LOOP

In this tutorial, you learned:

  1. What a for loop is and why it is used.

  2. The syntax and execution of a for loop.

  3. Using range() with start, stop, and step.

  4. Iterating through lists, strings, tuples, and dictionaries.

  5. Using conditions inside loops.

  6. Calculating totals and finding the largest number.

  7. Creating nested for loops.

  8. Using break and continue.

  9. Using enumerate() to access indexes and values.

  10. Building student reports and billing calculators.

  11. Avoiding common loop mistakes.

  12. Practicing Python programming with quizzes and assignments.

Conclusion:

The Python for loop is an essential programming tool for processing collections, repeating operations, and automating tasks. By practicing these examples and projects, you can develop a strong understanding of iteration and prepare for more advanced Python concepts.

←
Post 6 of 20
→