Course 4.2Lesson 4 of 5
Use a for loop when the number of rounds is known or when you go through the items of something, and use a while loop when the rounds depend on a condition. Many jobs can be done with either. The two usual faults of loops are the endless loop, where nothing in the body moves the condition towards False, and the off-by-one fault, where a loop makes one round too many or too few because of < and <=. To find them, follow the loop with a trace table, print the variable inside the loop, and test with a small number of rounds first.
Try the code and the simulations beside the lesson.
After this lesson you can
for loop and a while loop,You now know two loops. How do you choose?
for when you know the number of rounds, or when you go through the items of something: the numbers of a range(), the letters of a text.while when the number of rounds depends on a condition that is checked as you go: saving until there is enough, asking until the answer is right.Many jobs can be done with either. Here is the same job, adding the numbers 1 to 5, in both forms.
An endless loop is a loop whose condition never becomes False. The computer goes on and on. This is the loop, written as text because we do not want to run it.
count = 1
while count <= 3:
print(count)Nothing changes count, so count <= 3 is always True. On a computer, you stop such a program with Ctrl + C. On this site, the run stops after a time limit, with a message.
How to find the cause. Ask three questions.
count <= 3.count.Other causes: the line changes the variable in the wrong direction (count = count - 1), changes a different variable, or sits inside an if that is never True, or after a continue that skips it.
The loop runs, but one round too many or too few. The usual reason is < against <=.
Here is how to avoid it. Before you write the condition, write what the last round should be. If the last round has n = 5, the condition must be True for 5 and False for 6. That is n <= 5, or n < 6.
This is the off-by-one fault: the loop runs one round too many or one too few. Test the last round by hand.
print("n is", n) as the first line of the body. You see each round on the screen.while when for is simpler. More lines to go wrong.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
for for a known number of rounds or the items of something. while for a condition.while loop needs a start, a test and a change. Check all three.False.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
while loop needs?while n < 5: starts with n = 1 and adds 1. Which numbers does it show?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.