Python For Loops: How to Repeat Tasks in Your Code

Python For Loops: How to Repeat Tasks in Your Code
Photo from the web

Python for loops let you repeat a block of code a set number of times without typing the same lines again and again. If you have a list of ten items, a for loop visits each item one by one so you can print it, change it, or check it.

Think of a loop like a line cook at a burger shop. The cook takes one order ticket, makes the meal, and then moves right to the next ticket until the board is empty. In Python, you write the rule once, and the loop does the heavy work for you.

What Is a Python For Loop and How Does It Work?

A for loop steps through a group of items, one at a time. In Python, these groups are often lists, strings, or numbers created by the range function. Every time the loop runs, it puts the current item into a variable name you pick. Then it runs the code block inside the loop.

Let us look at a simple example with food items. Imagine you want to print three fruits on your screen:

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

When Python runs these three lines, it sets fruit to "apple" and prints it. Next, it changes fruit to "banana" and prints it. Last, it changes fruit to "cherry" and prints it. The loop stops automatically when there are no items left in the list.

If you want to handle unexpected problems inside your loops, you can read about Python Try Except: How to Catch Errors Before They Crash Code to keep your scripts running smooth. Catching bad data early stops your loop from breaking halfway through a big job.

Python For Loops: How to Repeat Tasks in Your Code
Photo from the web

How to Use Range to Repeat Code Specific Times

Sometimes you do not have a list ready. You just want to run code five times, or maybe a hundred times. The range() tool generates a sequence of numbers for you on the spot.

By default, range(5) gives you numbers starting at 0 up to 4. That is five numbers total. Here is how that looks in code:

for number in range(5):
    print("Loop number:", number)

Notice how computers start counting at zero. The output prints 0, 1, 2, 3, and 4. If you want to start at 1, you give range() two numbers: a start and a stop. Typing range(1, 6) will print 1 through 5. The stop number is never included in the loop result.

You can also add a third number to set the step size. If you want to count by twos from 2 to 10, write range(2, 11, 2). It will print 2, 4, 6, 8, and 10. This is super helpful when you only want to process every second item or count backward using negative step numbers.

Using Break and Continue to Control Your Loops

Sometimes you need to exit a loop early, or skip an item that does not fit your rules. Python gives us two key commands for this: break and continue.

The break keyword stops the loop cold. It pops you right out of the loop, even if there are fifty items left to check. This is great when you are looking for one specific thing and want to stop searching as soon as you find it.

names = ["Alex", "Sam", "Jordan", "Taylor"]
for name in names:
    if name == "Jordan":
        print("Found Jordan!")
        break
    print("Checking:", name)

In this small code block, Python checks "Alex", then "Sam". When it gets to "Jordan", it prints the match message and hits the break statement. It never checks "Taylor" because the loop ends instantly. This saves your computer time when working with large data sets.

The continue keyword acts differently. It skips the rest of the code inside the loop for the current item, but stays in the loop for the next item. If you want to check out more tips, visit our tech guide home for simple python tutorials to see how to organize your scripts cleanly.

scores = [85, 42, 90, 38, 77]
for score in scores:
    if score < 50:
        continue
    print("Passing score:", score)

Here, any score under 50 triggers the continue statement. Python stops reading the rest of the loop block and immediately starts the next round with the next score. Scores 42 and 38 get skipped entirely, while passing scores print to the screen.

Looping Through Text Strings Character by Character

In Python, a text string is treated as a collection of single letters. That means a for loop can walk through words just like it walks through lists of items.

If you put a word into a loop, Python gives you one character on every pass. Here is a quick example using a secret code idea:

word = "Python"
for letter in word:
    print(letter.upper())

This prints P, Y, T, H, O, and N on separate lines. You can check each letter to see if it is a vowel, count how many spaces appear in a sentence, or build a new string with flipped letters. It makes text processing very simple.

How to Use Nested For Loops for Grid Data

A nested loop is simply one for loop placed inside another for loop. The inner loop runs completely from start to finish every single time the outer loop steps forward once.

Think about a clock. The minute hand must go all the way around 60 times before the hour hand clicks forward just one position. That is how nested loops function in Python code.

for hour in range(1, 4):
    for minute in [0, 30]:
        print("Time:", hour, ":", minute)

The outer loop runs three times for hours 1, 2, and 3. For hour 1, the inner loop prints minute 0, then minute 30. Then the outer loop shifts to hour 2, and the inner loop runs both minutes again. In total, the print line runs six times.

Nested loops are very handy for working with rows and columns, like spreadsheets or game boards. But be careful not to nest too many loops together. Three or four levels of nested loops can make your program run slow quickly if your data sets are large.

Looping Through Dictionaries to Read Keys and Values

Lists are great, but Python dictionaries store data in pairs made of keys and values. A for loop lets you read those pairs easily.

If you loop over a standard dictionary directly, Python gives you only the keys. To get both the keys and the values together, use the .items() tool built into Python dictionaries.

user_ages = {"Alice": 25, "Bob": 30, "Charlie": 22}
for name, age in user_ages.items():
    print(name, "is", age, "years old.")

The variable name takes the key, while age takes the matching value. On the first pass, name is "Alice" and age is 25. On the second, name is "Bob" and age is 30. This makes formatting user data clean and readable.

When writing complex scripts with loops and dictionaries, errors will happen. Reading our article on Python Try Except: How to Catch Errors Before They Crash Code helps you build smart backups inside your data loops.

Using the Else Block with Python For Loops

Python has a neat feature that many other programming languages do not offer. You can add an else block right at the end of a for loop.

The code inside the else block runs only if the loop finishes all its iterations naturally. If the loop stops early because it hits a break command, the else block gets completely ignored.

items = ["book", "pen", "desk"]
search_target = "laptop"

for item in items:
    if item == search_target:
        print("Item found in stock!")
        break
else:
    print("Item is not in stock.")

Since "laptop" is not in our items list, the loop checks every single item without hitting the break statement. Once it finishes checking "desk", it jumps to the else line and prints "Item is not in stock."

This trick keeps you from having to create extra true-or-false flag variables just to check if a search succeeded or failed. If you want more helpful tips on basic syntax, check out our main programming resource collection for beginners to keep expanding your skills.

Common Mistakes to Avoid When Writing For Loops

Even experienced coders make small mistakes with loops. Learning what to look for will save you minutes of debugging time.

First, watch your indentation. Python relies on tab spaces to know what code stays inside the loop and what code sits outside. If a line is not indented correctly, Python might run it only once after the loop finishes instead of running it on every cycle.

Second, avoid modifying a list while you are actively looping through it. If you remove items from a list while your for loop moves forward, Python will skip elements because the indexes shift under its feet. Create a fresh, empty list and append the items you want to keep instead.

Third, remember that range(a, b) ends right before reaching number b. If you write range(1, 10), your code runs 9 times, not 10. Always raise the ending number by 1 if you need that final value included in your output.

Three Quick Tips You Can Use Today

  • Use enumerate() for index numbers: If you need to track item numbers along with the items, write for index, item in enumerate(my_list): instead of maintaining a counter by hand.
  • Keep loop bodies short: Move complex calculations into external functions so your for loop remains easy to read at a quick glance.
  • Test with tiny lists first: Run your loop logic on a list of two or three test items before running it on thousands of database rows.

Loops are one of the most useful tools in programming because they take repetitive work off your plate completely. Which daily task or dataset are you going to automate first using a Python for loop?

Post a Comment