Module 2 ยท Making the program decide Lesson 5 of 15
for and while loops
A for loop walks through a collection; a while loop repeats until a condition stops being true. Repeating something 100 times by hand is not a skill, it is an error waiting to happen.
The concept
A for loop walks through a collection and stops by itself: for n in range(1, 6): runs five times with n taking 1 to 5 โ note that range excludes the last number, which is deliberate and worth remembering. A while loop repeats for as long as its condition stays true, and you are responsible for making it false; while count <= 10: needs a line inside that increases count, or the program runs for ever.
The practical difference is which one you reach for. Looping over a known set โ ten marks, the rows of a file, the questions in a quiz โ is a for. Repeating until something happens โ until the user types quit, until a balance reaches zero โ is a while. Both accept break to exit early and continue to skip to the next round, and both are why a computer can do in a second what takes you an hour.
for n in range(1, 6): # 1, 2, 3, 4, 5 โ the last number is excluded
print(n, n * n)
count = 1
while count <= 3:
print("Round", count)
count += 1 # without this line the loop never endsCommon mistakes
The two mistakes to know: an endless while loop because nothing inside changes the condition (Ctrl+C stops it โ that is not a crash), and off-by-one errors from forgetting that range(1, 5) stops at 4. When a loop misbehaves, print the counter on the first three rounds instead of guessing.
Worked example
for n in range(1, 6): print(n * n) prints the first five squares. for name in ["Asha", "Ravi"]: walks a list, one item at a time.
Your practice task
Print a table of 7 from 1 to 10 with a for loop, then print the same table with a while loop and decide which reads better.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
A for loop walks through a collection and stops by itself: for n in range(1, 6): runs five times with n taking 1 to 5 โ note that range excludes the last number, which is deliberate and worth remembering.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.