Книга: Practical Programming, Fourth Edition
Назад: Variables and Computer Memory: Reme mbering Values
Дальше: A Single Statement That Spans Mult iple Lines

How Python Tells You Something Went Wrong

There are two kinds of errors in Python: syntax errors, which occur 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 dividing a number by zero or using a variable that doesn’t exist.

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

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

Variables must be assigned values before they can be used

The message is somewhat cryptic; Python error messages are intended 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 you what went wrong: the name moogah wasn’t recognized—a NameError occurred.

Here’s another error message you may see:

 >>>​​ ​​2​​ ​​+
  File "<python-input-0>", 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 informs you that you violated Python’s syntax rules—in this case, by attempting to add something to 2 without specifying what to add.

Earlier we claimed that 12 = x results in an error. Let’s try it:

 >>>​​ ​​12​​ ​​=​​ ​​x
  File "<python-input-1>", line 1
  12 = x
  ^^
 SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

A literal is any value, like 12 and 26.0. This error 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. A 12 is just a 12. In other words, a value can’t be on the LHS.

Incidentally, the Python interpreter is trying to be helpful and suggests that you may have used one equal sign instead of two. You will learn the difference later in .

Назад: Variables and Computer Memory: Reme mbering Values
Дальше: A Single Statement That Spans Mult iple Lines