This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 9: Incremental development

Test as you code

face Josiah Wang

Here is an example of what I mean by “test as you code”.

You might have written a line of code to read in a user input.

user_guess = input("Enter a number: ")

You should then make sure that this line works, for example by printing out the value.

user_guess = input("Enter a number: ")
print(user_guess)

So far so good. Now you might want to compare the value to your secret number (say 42 for simplicity).

user_guess = input("Enter a number: ")

if user_guess == 42:
    print("Correct")

Then you test your code with a wrong guess (34). It does not print anything, as expected (good!)

user@MACHINE:~$ python guessing_game.py
Enter a number: 34
user@MACHINE:~$

But when you try to enter 42, it does not print anything either (not good!)

user@MACHINE:~$ python guessing_game.py
Enter a number: 42
user@MACHINE:~$

So at this point, you have already started the debugging process. You already know that something is wrong with the comparison statement, so it will be easier to pinpoint the problem at this stage rather than waiting until you have finished writing your whole program to test and debug your code.

This makes the whole coding process more enjoyable, than trying to pinpoint the problem among other bits of code. This problem will be worse when you have multiple errors coming from different parts of your code! If you write AND test your code step by step, it will save you from trying to figure out all these errors.

So, testing should be part of your coding process. You should be testing your code incrementally as you write!

This is a form of incremental development, although I prefer to call it “test as you code”.