Avoiding pitfalls
Computers don't make mistakes
So, the good news is that computers don't make mistakes.
The bad news is that, because it's up to humans like us to tell computers what to do, mistakes can and often do creep in.
Bugs
These mistakes, or bugs, can cause a program to produce unexpected results or stop working altogether.
OK computer: remember 0 as my_number repeat until my_number is less than 0: add 1 to my_number then display my_number
//Output Below
...
See that? Because my_number
will never be less than 0
, this so-called infinite loop will never get to display my_number
.
Debugging
Debugging, which means finding and fixing bugs, is an important part of programming. Can you spot a bug in this program?
OK computer: remember "Walter" as my_name add " White" to my_name display my name
- Yes, in
display my name
Perfect! Because my name
misses an underscore, the computer can't make sense of line 3.
Syntax bugs
Instructions need to follow special rules. When we break these rules, computers don't know what we want them to do.
What rule would make sense here?
OK computer: if it is teatime then display "time for afternoon tea"
//Output Below
time for afternoon tea
See that? These so-called syntax bugs can be typos or words that computers don’t understand.
Logic bugs
When a program has a logic bug, it doesn't crash but doesn't act as intended either. Can you spot such a bug in this program?
OK computer: remember 42 as my_age if my_age is greater than 65 or my_age is greater than 12 then display "20% discount" else display "no discount"
- Yes, we need to check if
my_age
is less than12
Fantastic! We need to check if my_age
is less than 12
or anybody above 12
gets a discount.
Documenting programs
As programs become more and more powerful, their instructions become harder and harder to read. How might we be able to prevent that?
- By providing comments for complicated instructions
Yes! Using comments and meaningful names for variables and functions, programs become easier to understand and debug.
Testing
Before we release a program, we should perform a range of tests. Why might this be important?
- Because there may be severe bugs in the program
Great! Even though we won't be able to find every bug in a program, we shouldn't release a program with severe bugs.
Comments