Reading Errors
Mistakes are a normal part of programming. Even experienced programmers make them every day. What matters is finding and fixing them quickly, and error messages help you with that.
When Python can't run your program, it shows a red error message below the output. For example, this program has a typo on its second line:
price = 120
print(pirce)Python stops with this message:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
NameError: name 'pirce' is not defined. Did you mean: 'price'?It may look scary, but it's easy to read when you start from the bottom:
- The last line says what went wrong. Before the colon is the type of the error, here
NameError. After the colon is a description: the namepirceisn't defined, so Python doesn't know it. Sometimes Python even suggests a fix:Did you mean: 'price'? - The line above it says where the error happened:
line 2.File "<exec>"andin <module>only say that it's in your program, so you can skip them. - The first line,
Traceback (most recent call last), is just a heading: what follows traces the error back to the place where it happened.
A SyntaxError looks a little different. It means that the code breaks the rules for writing Python, its syntax. Usually a quote or a parenthesis is missing:
print("Hello"Python stops with this message:
Traceback (most recent call last):
File "<exec>", line 1
print("Hello"
^
SyntaxError: '(' was never closedPython shows the line with the mistake and marks the place with ^: here, a parenthesis that is never closed. A missing quote gives SyntaxError: unterminated string literal (detected at line 1): a text (a string) that never ends. Python checks the whole program before running it, so when there is a syntax error, nothing runs at all, not even the lines before the mistake.
Two other errors are common:
NameError: you used a name that Python doesn't know. Usually it's a typo (pirceinstead ofprice, orPrice, because uppercase and lowercase letters matter), a variable used before it was created, or text without quotes:print(Anna).TypeError: you tried to do something that the type of a value doesn't allow, such as joining a string and a number:"5" + 3.
With a NameError or a TypeError, the program runs until it reaches the mistake, and then it stops. What it printed before stays in the output. That's a useful clue: the mistake is after the last print() that still printed something.
When you get an error, read the last line first, then find the line it names, and fix the mistake. Then run the program again: there may be another mistake further on.
Instructions
The program in the editor has three mistakes. Run it, read the error message, fix the mistake and run the program again. Repeat this until the program prints:
Player: Anna
Points: 10
Points after the bonus: 15Start programming for free
10/11