Python Lesson 5: Loops

Python Lesson 5: Loops featured illustration

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 Python Beginner Course · Lesson 5 of 12

Advertisement
In this article
  1. for loops
  2. range()
  3. List comprehensions
  4. while loops
  5. enumerate and zip
  6. Where beginners go wrong
  7. Practice
  8. Continue learning

In Excel you fill a formula down 500 rows. In Python you write a loop: “for each row, do this”. Loops are where Python starts saving real time.

for loops

marks = {"Aarav": 78, "Diya": 91, "Kabir": 45, "Meera": 66, "Rohan": 33}
passed = 0
for name, m in marks.items():
    result = "Pass" if m >= 40 else "Fail"
    if result == "Pass":
        passed += 1                # same as passed = passed + 1
    print(f"{name:<6} {m:>3}  {result}")
print("Passed:", passed, "of", len(marks))

The indented block runs once per item. {name:<6} pads text to 6 characters so columns line up.

range()

for month in range(1, 13):      # 1 to 12 (the end is excluded)
    print(month)

List comprehensions

squares = [n * n for n in range(1, 6)]                 # [1, 4, 9, 16, 25]
big = [m for m in marks.values() if m >= 75]           # filter
names = [n.upper() for n in marks]                      # transform

One line that builds a new list, like an Excel spill formula. Use it for simple transformations; switch to a normal loop when the logic grows.

Advertisement

while loops

balance, month = 100000, 0
while balance > 0:
    balance -= 9000
    month += 1

Repeats while the condition is true. Make sure something inside changes the condition, or it never stops (press Ctrl+C to break out).

💡 break leaves a loop early (stop at the first overdue invoice); continue skips to the next item (ignore blank rows).

enumerate and zip

for i, region in enumerate(["North", "South"], start=1):
    print(i, region)                         # 1 North, 2 South
for name, m in zip(["A", "B"], [70, 80]):    # walk two lists together
    print(name, m)

Where beginners go wrong

Problem Cause
Total only counts the last item total = 0 placed inside the loop; set it before
Loop never ends while condition never becomes false
Changing a list while looping over it Loop over a copy: for x in items[:]

Practice

Download the script (and data file, if listed) below into one folder. Open a terminal in that folder and run python lesson-NN.py. Compare with the expected output, then change something and run it again: that’s how Python is learned.

Advertisement

📎 Practice files for this article

⬇ Download all 2 files (ZIP · 715 B)

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong