Loops

Loops in Python: Imagine you were tasked with writing your name 100 times on a chalkboard. Doing this manually would be exhausting and prone to errors.

Concept Explanation

Imagine you were tasked with writing your name 100 times on a chalkboard. Doing this manually would be exhausting and prone to errors. In programming, we have a way to automate these repetitive tasks effortlessly: Loops.

The For Loop is specifically designed to iterate (repeat) over a sequence of items. This sequence could be a list of names, a range of numbers, characters in a string, or even lines in a file. Instead of writing the same line of code over and over, you tell Python: "For every item in this collection, do this specific task."


Syntax or Core Structure

The for ... in ... loop

  1. The Item Variable: A temporary name (fruit, i, x) representing the current item being processed.
  2. The Sequence: The list, string, or range you are looping through.
  3. The Block: The indented code that runs for every single item.
# Simple List Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I enjoy eating {fruit}s.")

# Range Loop (exclusive of the stop number)
for i in range(5):  # 0, 1, 2, 3, 4
    print(f"Counting: {i}")

Code Example #1 (Basic)

Let's see how we can use a loop to perform a quick mathematical operation on a list of numbers.

prices = [10, 25, 50, 100]
discounted_prices = []

for price in prices:
    new_price = price * 0.9 # 10% discount
    discounted_prices.append(new_price)

print("Original Prices:", prices)
print("Discounted Prices:", discounted_prices)

Code Example #2 (Intermediate)

You can nest loops inside of each other, or use logic inside a loop to filter results.

# Finding even numbers in a large range
print("Looking for even numbers...")

for num in range(1, 21):
    if num % 2 == 0:
        print(f"{num} is even!")
    else:
        # We can skip odd numbers or do something else
        pass

Real World Example

Imagine you are building a social media feed where you need to display a list of usernames and check if any of them are your "Best Friend."

# 📱 Social Media Feed Simulation
users = ["alex22", "sam_rocks", "jordan_dev", "sarah_p", "mike_t"]
best_friend = "jordan_dev"

print("--- Your Friends List ---")

for user in users:
    if user == best_friend:
        print(f"⭐ {user} (Best Friend)")
    else:
        print(f"👤 {user}")

print("-------------------------")

Common Mistakes

  1. Off-By-One Errors: Remembering that range(5) goes from 0 to 4, NOT 5. If you need 1 to 5, you must write range(1, 6).
  2. Indentation: If you forget to indent the body of the loop, Python will throw an IndentationError. If you indent too much code, lines that were supposed to run after the loop will run inside it repeatedly.
  3. Modifying the List While Looping: Trying to remove items from a list while you are currently looping through it can cause Python to skip items or crash. It's safer to create a new list or loop through a copy (for x in my_list[:]:).

Best Practices

  • Meaningful Names: Use descriptive names for your loop variable. for user in users: is much better than for x in users:.
  • Use Enumerate: If you need to keep track of the index (the position number), use enumerate() instead of creating a separate counter variable.
  • for index, user in enumerate(users):
  • Keep it Lean: Only put code inside the loop that absolutely needs to repeat. Moving constant calculations outside the loop makes your program faster.

Practice Exercises

  1. The Multiplier: Write a loop that prints the "5 Times Table" (5 1, 5 2 ... up to 5 * 10).
  2. String Looping: Write a loop that takes the string "CodeAcademix" and prints every character one by one.
  3. Summation: Create a list of 5 numbers. Write a loop that calculates the total sum of all those numbers and prints it at the very end.
  4. Countdown: Use the range() function's optional third parameter (step) to create a countdown from 10 to 1.