Lesson 4
Repeated Practice Makes Perfect
Chapter 3: While loops
While you code
I spent quite a lot of time discussing infinite loops in this chapter. This is because it is one of the most common errors in a program.
Now, remember my “test/debug as you code” advice from the previous lesson? This is one way of making sure that infinite loops do not happen in the first place!
When you write your loop, you can start with a pass
statement.
x = 1
while x < 3:
pass
And since you know that this will definitely cause an infinite loop, you can write the increment statement immediately before writing anything else. This guarantees that you will not be stuck in an infinite loop (unless you change the value of x
before that)! Run your program to make sure that it is working.
x = 1
while x < 3:
x = x + 1
Then you can code the other bits in your while
loop body. Hey, nobody ever said that you have write your code from top to bottom! 😝
x = 1
while x < 3:
print(x)
x = x + 1
Remember to test while you code, in case you accidentally changed the value of x
before the increment statement!