Choosing While or For

The rule is simple:

Use for when you're walking a collection or repeating a known number of times.

Use while when you're waiting for a condition to change and can't know the count ahead of time.

EXAMPLE
loading editor…
YOUR TURN
Your turn → You couldn't have written this with a for loop, the number of months is the ANSWER, not the input. Change the deposit to 50 and run it. Then store the deposit in its own variable so the loop uses that instead of a fixed number.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

break works in while loops too, and pairs well with a deliberate forever-loop when the exit condition lives in the middle of the body.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change it so the correct attempt is the fifth one, and print a final message after the loop finishes.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Challenge

A fund starts at 0 and needs 500. Each contribution adds 75. Use a while loop to create contributions holding how many are needed, and balance holding the final amount.

Name it exactly: contributions, balance

2 visible + 1 hidden
loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back