
Python
Follow these conventions to write code that others can understand and maintain.
# ❌ BAD - unclear what x and y are
for x in data:
y = x * 2
print(y)
# ✅ GOOD - clear variable names
for item in data:
doubled = item * 2
print(doubled)# ❌ BAD - too much logic in one loop
for student in students:
grade = student['grade']
if grade > 80:
grade = grade + 5
student['final_grade'] = grade
if grade >= 90:
student['category'] = 'A'
else:
student['category'] = 'B'
# ✅ GOOD - separate concerns
for student in students:
student['final_grade'] = calculate_final_grade(student)
student['category'] = assign_category(student)# ❌ BAD - using while when for is clearer
i = 0
while i < len(items):
print(items[i])
i = i + 1
# ✅ GOOD - for loop is more Pythonic
for item in items:
print(item)# ❌ BAD - hard to follow
for i in range(10):
for j in range(10):
for k in range(10):
if condition1:
if condition2:
print("Found it!")
# ✅ GOOD - extract to function
for i in range(10):
for j in range(10):
if process_item(i, j):
print("Found it!")
def process_item(i, j):
for k in range(10):
if condition1 and condition2:
return True
return False# Calculate running average
total = 0
count = 0
for score in scores:
total = total + score # Add score
count = count + 1 # Count items
average = total / count # Divide
# Or better yet, use clearer variable names:
sum_of_scores = 0
for score in scores:
sum_of_scores = sum_of_scores + score
average = sum_of_scores / len(scores)# ❌ NOT NEEDED - Python has better ways
total = 0
for number in numbers:
total = total + number
average = total / len(numbers)
# ✅ USE BUILT-INS - cleaner and faster
average = sum(numbers) / len(numbers)| Practice | Benefit |
|---|---|
| Meaningful names | Code explains itself |
| Simple loops | Easier to understand |
| Right loop type | Clearer intent |
| Minimal nesting | Avoids confusion |
| Comments | Documents complex logic |
| Built-ins | Faster, more readable |
You've mastered beginner loops! Switch to Advanced Path for deeper knowledge.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward