Loops repeat code automatically — essential for processing data, creating patterns, and solving problems that involve repetition. Python has two loop types: for (known iterations) and while (until condition becomes False).
for loop: for i in range(5): print(i) → prints 0,1,2,3,4. range(start, stop, step): range(2,10,2) → 2,4,6,8. Iterate over strings: for ch in "Hello": print(ch). while loop: repeats while condition is True. count = 0; while count < 5: print(count); count += 1. Danger: infinite loop if condition never becomes False!
break: exit the loop immediately. continue: skip rest of current iteration, go to next. else with loop: runs when loop ends normally (no break). Nested loops: loop inside a loop — outer runs once, inner runs completely. Star pattern: for i in range(1,6): print("*" * i) → triangle. Use loops for: sum of numbers, factorial, counting, searching, table generation.
Use for when you know the number of iterations in advance (e.g., iterate through a list, repeat 10 times, process each character). Use while when repeating until a condition changes (e.g., keep asking for input until valid, game loop until player loses). Rule of thumb: if you can use for, prefer it — it's safer (less risk of infinite loops) and more Pythonic.
Book a Trial + Diagnostic session. Get a personalized Learning Path with clear milestones, tutor match, and a plan recommendation — all within 24 hours.
Book Trial + Diagnostic →