The Art of Simple Python Loops
There's a quiet elegance in well-written loops. Like a path through a garden, they should guide the reader naturally from beginning to end, each step clear and purposeful.
The Foundation: The Simple For Loop
The most beautiful code often starts with the most basic tools. A simple for loop tells a complete story:
names = ['Alice', 'Bob', 'Charlie']
for name in names:
print(f"Hello, {name}")
This reads like natural language. "For each name in the list of names, say hello." No mystery, no mental gymnastics required. The loop variable name
describes exactly what it contains.
When You Need Position Too
Sometimes you need to know where you are in the journey:
tasks = ['Review code', 'Write tests', 'Deploy']
for position, task in enumerate(tasks):
print(f"{position + 1}. {task}")
The enumerate
function gives you both the item and its position. Start counting from zero? Use position
. Need to start from one? Add one. Simple arithmetic, clear intention.
Walking Through Two Lists Together
When you have related information in separate lists, walk through them side by side:
students = ['Anna', 'Ben', 'Cara']
grades = [92, 87, 94]
for student, grade in zip(students, grades):
print(f"{student}: {grade}%")
This creates natural pairs. No indexing, no potential for off-by-one errors. The relationship between student and grade is immediately visible.
Collecting Results
Often you need to transform each item and save the results:
temperatures_f = [68, 72, 75, 71]
temperatures_c = []
for temp_f in temperatures_f:
temp_c = (temp_f - 32) * 5 / 9
temperatures_c.append(temp_c)
Each step is explicit: take a Fahrenheit temperature, convert it, add it to the results. The conversion formula stands alone on its own line, easy to verify or modify.
Filtering as You Go
Sometimes you only want certain items:
scores = [45, 78, 92, 34, 88, 67]
passing_scores = []
for score in scores:
if score >= 70:
passing_scores.append(score)
The condition is clear and prominent. Anyone reading this immediately understands that 70 is the passing threshold. No hidden logic, no compressed syntax to decode.
Working with Dictionaries
Dictionaries have their own natural rhythm:
inventory = {'apples': 50, 'oranges': 30, 'bananas': 25}
for item, quantity in inventory.items():
if quantity < 40:
print(f"Order more {item}")
The .items()
method gives you both key and value as a natural pair. The logic flows: check each item's quantity, flag those running low.
Building Something New
Sometimes you're creating structure as you iterate:
raw_data = ['apple:5', 'orange:3', 'banana:7']
parsed = {}
for entry in raw_data:
fruit, count = entry.split(':')
parsed[fruit] = int(count)
Each transformation is a separate, understandable step. Split the string, convert the count, store the result. If something goes wrong, you can easily trace which step failed.
Nested Loops for Structure
When working with rows and columns, nested loops feel natural:
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in grid:
for number in row:
print(number, end=' ')
print() # New line after each row
The structure mirrors the data. Outer loop for rows, inner loop for items in each row. The indentation shows the hierarchy clearly.
The While Loop for Ongoing Work
Sometimes you don't know how many iterations you'll need:
user_input = ""
while user_input != "quit":
user_input = input("Enter command (or 'quit'): ")
if user_input == "help":
print("Available commands: help, status, quit")
elif user_input == "status":
print("System running normally")
The condition is simple and clear. The loop continues until the user chooses to stop. Each possible input gets its own clear branch.
The Beauty of Simplicity
Good loops don't try to impress. They serve the reader by making the code's intention immediately clear. Each variable has a meaningful name. Each step follows logically from the last. The code reads like a conversation between you and your future self.
When you write loops this way, debugging becomes easier, modifications feel natural, and new team members can contribute quickly. The code becomes not just functional, but genuinely readable—a small work of art that happens to solve problems.
This is the path toward beautiful code: not through clever tricks or advanced techniques, but through clarity, intention, and respect for the person who will read your code tomorrow.
Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.
Comments
Post a Comment