AI Ustoz UZ: learn artificial intelligence in Uzbek

Testing code and finding a bug

Intermediate level · lesson 3 · about 14 min

“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 otdi

Typical 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
  1. range(n) goes from 0 to n-1: for 1..n you need range(1, n + 1). (correct answer)the last value is not included and the start is 0.
  2. range only works with even numbers.there is no such limit.
  3. Nothing is wrong, the code is correct.the result will be off by one.

Code exercises

  1. 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 need range(1, n + 1).
  2. 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: and return 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.