Back to Study Material Python

Loops

Python's for loop iterates over any iterable object — lists, strings, tuples, ranges, dictionaries, sets, and custom objects that implement the iterator ...

Loops

The for Loop

Python's for loop iterates over any iterable object — lists, strings, tuples, ranges, dictionaries, sets, and custom objects that implement the iterator protocol. Syntax: for item in iterable: (indented block). Unlike C-style for loops, Python's for loop does not use a counter index; it directly hands you each element. If you need the index, use enumerate: for i, val in enumerate(my_list): gives both the index i and the value val.

The range Function

range() generates a sequence of integers. range(stop) generates 0 to stop-1. range(start, stop) generates start to stop-1. range(start, stop, step) generates values spaced by step. Example: range(1, 10, 2) generates 1, 3, 5, 7, 9. range objects are lazy — they do not create a list in memory; they compute values on demand. To get a list: list(range(5)) gives [0, 1, 2, 3, 4]. Use range when you need to repeat something a fixed number of times.

The while Loop

The while loop executes its body as long as a condition remains True. Syntax: while condition: (indented block). It is used when the number of iterations is not known in advance — for example, reading user input until a valid value is entered, or processing data until a sentinel value is encountered. Always ensure the loop body modifies something that eventually makes the condition False, or use break, to avoid an infinite loop.

Iterating over Dictionaries

When you loop over a dictionary directly (for key in d:), you iterate over its keys. To get values: for v in d.values(). To get both key and value simultaneously: for k, v in d.items(). This items() pattern is extremely common and idiomatic. Modifying a dictionary while iterating over it raises RuntimeError. If you need to modify it, iterate over a copy: for k in list(d.keys()):. Python 3.7+ guarantees dictionaries maintain insertion order.

Worked Example: Finding Primes

A simple prime sieve using nested loops: primes = []; for n in range(2, 50): is_prime = True; for d in range(2, int(n**0.5)+1): if n % d == 0: is_prime = False; break; if is_prime: primes.append(n); print(primes). The inner loop uses a break once a divisor is found, and the else clause (if added) would confirm primality. This example combines range, for loops, break, and a flag variable.

Exam Tip

A key exam distinction: for vs while. Use for when you know the number of iterations or are iterating over a collection. Use while when iterating until a condition changes. Exam questions often ask: what does range(5) produce? It produces 0, 1, 2, 3, 4 — not including 5. Another question: what is the output of for x in range(0, 10, 3): print(x)? It prints 0, 3, 6, 9. Always work through range arguments carefully: (start, stop_exclusive, step).