![]() |
|
CHAPTER 11 — Loops & Repetition - Printable Version +- The Lumin Archive (https://theluminarchive.co.uk) +-- Forum: The Lumin Archive — Core Forums (https://theluminarchive.co.uk/forumdisplay.php?fid=3) +--- Forum: Courses — Structured Learning (https://theluminarchive.co.uk/forumdisplay.php?fid=69) +---- Forum: Beginner’s Guide to Coding — Python From Zero to Skill (https://theluminarchive.co.uk/forumdisplay.php?fid=72) +---- Thread: CHAPTER 11 — Loops & Repetition (/showthread.php?tid=229) |
CHAPTER 11 — Loops & Repetition - Leejohnston - 11-15-2025 Chapter 11 — Loops & Repetition Loops let your program repeat actions without writing the same code over and over. There are two main loops in Python: • for loops — repeat a set number of times • while loops — repeat until a condition changes --- 11.1 The for Loop A for loop repeats a known number of times. Example: Code: for i in range(5):Output: Code: Hellorange(5) gives: 0, 1, 2, 3, 4 --- 11.2 Loop Variable Inside the loop, i changes each time: Code: for i in range(5):Output: Code: 0You can rename it: Code: for day in range(1, 8):--- 11.3 range() Variations Start → End: Code: for x in range(3, 8):Output: Code: 3Start → End → Step: Code: for n in range(0, 20, 5):Output: Code: 0--- 11.4 Looping Through Strings Code: for letter in "Python":--- 11.5 Looping Through Lists Code: fruits = ["apple", "banana", "cherry"]--- 11.6 The while Loop Repeats while a condition is True. Code: count = 1--- 11.7 Infinite Loops (Be Careful!) ❌ Warning: Code: while True:You must break out manually. --- 11.8 Using break Stops the loop immediately: Code: while True:--- 11.9 Using continue Skip the current loop and continue with the next one: Code: for n in range(1, 8):Output: Code: 1--- 11.10 Practical Pattern — Counting Down Code: for n in range(10, 0, -1):--- 11.11 Mini Project — Times Tables Ask user for a number. Print its times table up to 12. Code: 7 × 1 = 7--- 11.12 Challenge — Password Attempt System Rules: • user gets 3 attempts • password is “python123” • use a while loop • show attempts left • break when successful • lock them out after 3 fails --- 11.13 Chapter Summary • for loops = repeat a set number of times • while loops = repeat until condition changes • range() controls the loop • break stops early • continue skips one loop • loops work with lists, numbers, and strings Next: Chapter 12 — Lists: Storing Multiple Items Lists are like containers that hold many values at once — essential for real programs. --- Written and Compiled by Lee Johnston — Founder of The Lumin Archive |