Python For Loop Tutorial for Beginners: 10 Real Examples

A for loop can process strings, lists, dictionaries, files, and generated numbers. Here are ten useful patterns: print each name; sum numbers; filter positive values; convert temperatures; enumerate a list; iterate over dictionary items; count words; flatten a small list; read lines from a file; and build a result list.

scores = [72, 91, 64, 88]
passed = [score for score in scores if score >= 70]

for index, score in enumerate(scores, start=1):
    print(index, score)

Use enumerate() instead of manually maintaining a counter. Use .items() for dictionary keys and values. Use list comprehensions for short transformations, but choose a normal loop when the logic has several steps or needs error handling.

Avoid changing the collection you are currently iterating over. Create a new list or iterate over a copy. When loops become deeply nested, move logic into functions or choose a clearer data structure.

The best loop is the one a future reader can understand quickly. Practice by translating a real task – cleaning a list of usernames or calculating totals – into a small, testable function.

Leave a Comment

Scroll to Top