Course 5.3Lesson 4 of 4
A program that does not work is normal, and finding the fault is a skill. A checklist helps: read the error message from the bottom, find the line, reproduce the fault with the smallest input, follow the program by hand with a trace table, print the values inside the loop, check the edges, and change one thing at a time. When the program runs but the answer is wrong, compare with the expected answer worked out by hand. Keep the thinking in small functions so that each can be tested alone. After the Foundations, the next steps are dictionaries, tuples and sets, handling errors with try and except, modules, and larger projects in the Essentials level.
Try the code and the simulations beside the lesson.
After this lesson you can
print, andEvery programmer, on every day, writes programs that do not work at first. The difference between a beginner and an expert is not that the expert makes no mistakes. It is that the expert has a method for finding them. Here is the method.
NameError, TypeError, IndexError or ValueError. To fix it, read the message from the bottom. It says the kind of error and what went wrong. Above it is the line.When the program does not work, go down this list, one step at a time.
print in the loop shows what is happening. Remove it when done.This program should show the average of the positive numbers only. The positive numbers are 4, 9 and 7, so the expected answer is 20 divided by 3, about 6.67.
Now think about a case that the program does not handle. What if the list has no positive number, such as [-1, 0, -5]? Then count stays 0 and the last line divides by zero: ZeroDivisionError. This is an edge case, and the checklist told us to look for it. The cure is an if count > 0: before the division, with a message for the other case.
The expected answer, n * (n + 1) // 2, comes from mathematics, not from the program. That is what makes it a fair check.
total and count tell you what the numbers mean. a and b do not.You have finished the Foundations. You can store data in variables, make decisions, repeat with loops, keep many values in lists, and organise a program with functions. You have built three programs. That is the core of programming. The next level, Python Essentials, goes further:
try and except, so that a wrong input does not stop the program.The best way to learn is to build. Choose a small project that you care about: a quiz for your class, a unit converter, a game, a tracker for your own marks. Plan it, build it in small steps, test it, and show it to a friend.
Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.