๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 2 ยท Lesson 5 of 15

0% Exit to course

Module 2 ยท Making the program decide Lesson 5 of 15

for and while loops

Learning objective

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.

Python
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 ends

Common 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.

Create free account or sign in

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.