Testing code and finding a bug
“The code runs” does not mean “the code is correct”. To test it, write examples in advance and compare the result. In Python assert condition raises an error if the condition is false: handy for small tests.
def kvadrat(son):
return son * son
assert kvadrat(3) == 9
assert kvadrat(-2) == 4
assert kvadrat(0) == 0
print("hamma testlar otdi")Outputhamma testlar otdiTypical bugs: off-by-one (range(n) goes from 0 to n-1, while range(1, n + 1) goes from 1 to n) and empty input (an average of an empty list leads to division by zero). Such bugs appear in code written by artificial intelligence too.
When you find a bug, reproduce it on one small example, find the cause and fix only that spot. Then re-test all the examples: the fix must not break anything else.
Remember
- Write examples in advance; test with
assert. - Typical bugs: off-by-one and empty input.
- After fixing, re-test every example.
Exercise
You want to count from 1 to n with range(n). What is wrong?
Answer and explanation
range(n)goes from 0 to n-1: for 1..n you needrange(1, n + 1). (correct answer)the last value is not included and the start is 0.rangeonly works with even numbers.there is no such limit.- Nothing is wrong, the code is correct.the result will be off by one.
Code exercises
- The function
yigindi(n)should add the numbers from 1 to n but gives a wrong result. Find the bug and fix it.
Hint:range(n)goes from 0 to n-1. For 1..n you needrange(1, n + 1). - Make
ortacha([])not raise an error: for an empty list it should return 0. Do not change the other cases.
Hint: At the start of the function check for emptiness:if not royxat:andreturn 0.
Do the exercise in the app.
Practical task
Write 3 assert lines for one of the functions from earlier lessons (one for an edge case) and run them.
- I wrote 3 asserts
- One is for an edge case
Glossary
Interactive mode: search, progress and Python exercises.
