Monday, August 25, 2025

๐ŸFOR LOOP

For Loop in Python

Loops allow us to repeat a block of code multiple times without rewriting it. In this post, we’ll focus on the for loop.

Introduction

A for loop is used to iterate (repeat) over a sequence such as a list, tuple, string, dictionary, or even a range of numbers. Instead of writing the same line of code again and again, a loop lets you automate the repetition.

Syntax


for variable in sequence:
    # block of code to execute

- variable → takes each value from the sequence one by one.
- sequence → can be a list, string, range, or any iterable.
- Indentation is required for the block of code.

Basic Examples

1. Iterating over a list


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

2. Using range()


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

range(5) generates numbers from 0 to 4.

3. Iterating over a string


for letter in "Python":
    print(letter)

Common Mistakes

  • Forgetting the colon:for i in range(5)for i in range(5):
  • Indentation errors:
    
    for i in range(3):
    print(i)   # ❌ IndentationError
    
    Correct:
    
    for i in range(3):
        print(i)   # ✅ properly indented
    
  • Using capitalized keyword: For instead of for → ❌ SyntaxError.
  • Using the wrong iterable: Example: for i in 1234: → ❌ Error, because integers are not iterable. ✅ Fix: Use range(1234).

More Use Cases

1. Sum of numbers


total = 0
for i in range(1, 6):
    total += i
print("Sum is:", total)

2. Loop with if condition


for i in range(10):
    if i % 2 == 0:
        print(i, "is even")

3. Looping with break


for i in range(1, 10):
    if i == 5:
        print("Stopping at 5")
        break
    print(i)

4. Looping with continue


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

continue skips the current iteration.

๐Ÿ’ก Practice Challenges

  1. Write a program to print numbers from 1 to 20 using a for loop.
  2. Print the square of numbers from 1 to 10.
  3. Loop through a string and count how many vowels it contains.
  4. Create a multiplication table for a number entered by the user.

What’s Next?

After the for loop, we’ll explore the while loop, another powerful way to repeat code in Python.

➡️ Next: While Loop

⬅️ Back to Main Page

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??