Loops
for over a list — When you need to do something with each item in a sequence (list, tuple, etc.).
for fruit in ['apple', 'banana', 'cherry']: print(fruit)With index using enumerate:
fruits = ['apple', 'banana', 'cherry']for index, fruit in enumerate(fruits): print(index, fruit) # 0 apple, 1 banana, 2 cherryfor with range — When you need a loop that runs N times or over numeric indices (0 to n-1, or 1 to n-1).
for i in range(5): # 0, 1, 2, 3, 4 print(i)
for i in range(1, n): # 1 .. n-1 (e.g. split between i-1 and i) ...for over a string — When you need to process or check each character in a string.
for char in "hello": print(char) # h, e, l, l, ofor over a dictionary — When you need to loop over keys, values, or key–value pairs of a dict.
person = {'name': 'Alice', 'age': 30}
# Keys onlyfor key in person: print(f"Key: {key}")
# Keys and valuesfor key, value in person.items(): print(f"{key} → {value}")
# Keys in sorted orderfor key in sorted(person): print(key)Parallel iteration with zip — When you have two (or more) lists of the same length and want to loop over them together, one pair at a time.
names = ['Alice', 'Bob']scores = [85, 92]
for name, score in zip(names, scores): print(f"{name} scored {score}")Reading a file line by line — When you need to process a text file one line at a time without loading the whole file into memory.
with open(filename, 'r') as file: for line in file: print(line.rstrip()) # or process linewhile loop — When you need to repeat until a condition becomes false (e.g. “keep going while count < 3” or “until user quits”).
count = 0while count < 3: print("Count:", count) count += 1