How Python Tells You Something Went Wrong

Broadly speaking, there are two kinds of errors in Python: syntax errors, which happen when you type something that isn’t valid Python code, and semantic errors, which happen when you tell Python to do something that it just can’t do, like divide a number by zero or try to use a variable that doesn’t exist.

Here is what happens when we try to use a variable that hasn’t been created yet:

 >>>​​ ​​3​​ ​​+​​ ​​moogah
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 NameError: name 'moogah' is not defined

This is pretty cryptic; Python error messages are meant for people who already know Python. (You’ll get used to them and soon find them helpful.) The first two lines aren’t much use right now, though they’ll be indispensable when we start writing longer programs. The last line is the one that tells us what went wrong: the name moogah wasn’t recognized.

Here’s another error message you might sometimes see:

 >>>​​ ​​2​​ ​​+
  File "<stdin>", line 1
  2 +
  ^
 SyntaxError: invalid syntax

The rules governing what is and isn’t legal in a programming language are called its syntax. The message tells us that we violated Python’s syntax rules—in this case, by asking it to add something to 2 but not telling it what to add.

Earlier, in Warning: = Is Not Equality in Python! , we claimed that 12 = x results in an error. Let’s try it:

 >>>​​ ​​12​​ ​​=​​ ​​x
  File "<stdin>", line 1
 SyntaxError: can't assign to literal

A literal is any value, like 12 and 26.0. This is a SyntaxError because when Python examines that assignment statement, it knows that you can’t assign a value to a number even before it tries to execute it; you can’t change the value of 12 to anything else. 12 is just 12.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.57.172