Chapter 2. Variables and Statements

In the previous chapter, we used operators to write expressions that perform arithmetic computations.

In this chapter, you’ll learn about variables and statements, the import statement, and the print function. And I’ll introduce more of the vocabulary we use to talk about programs, including “argument” and “module.”

Variable Names

Variable names can be as long as you like. They can contain both letters and numbers, but they can’t begin with a number. It is legal to use uppercase letters, but it is conventional to use only lowercase for variable names.

The only punctuation that can appear in a variable name is the underscore character, _. It is often used in names with multiple words, such as your_name or airspeed_of_unladen_swallow.

If you give a variable an illegal name, you get a syntax error. The name million! is illegal because it contains punctuation:

million! = 1000000
       
  Cell In[15], line 1
    million! = 1000000
           ^
SyntaxError: invalid syntax
       

76trombones is illegal because it starts with a number:

76trombones = 'big parade'
        
  Cell In[16], line 1
    76trombones = 'big parade'
     ^
SyntaxError: invalid decimal literal
        

class is also illegal, but it might not be obvious why:

        class = 'Self-Defence Against Fresh Fruit'
        
  Cell In[17], line 1
    class = 'Self-Defence Against Fresh Fruit'
          ^
SyntaxError: invalid syntax
        

It turns out that class is a keyword, which is a special word used to specify the structure of a program. Keywords can’t be used as variable names.

Here’s a complete list of Python’s keywords:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

You don’t have to memorize this list. In most development environments, keywords are displayed in a different color; if you try to use one as a variable name, you’ll know.

Debugging

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish among them in order to track them down more quickly:

Syntax error

“Syntax” refers to the structure of a program and the rules about that structure. If there is a syntax error anywhere in your program, Python does not run the program. It displays an error message immediately.

Runtime error

If there are no syntax errors in your program, it can start running. But if something goes wrong, Python displays an error message and stops. This type of error is called a runtime error. It is also called an exception because it indicates that something exceptional has happened.

Semantic error

The third type of error is “semantic,” which means related to meaning. If there is a semantic error in your program, it runs without generating error messages, but it does not do what you intended. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.

As we’ve seen, an illegal variable name is a syntax error:

million! = 1000000
        
  Cell In[43], line 1
    million! = 1000000
           ^
SyntaxError: invalid syntax
        

If you use an operator with a type it doesn’t support, that’s a runtime error:

'126' / 3
        
TypeError: unsupported operand type(s) for /: 'str' and 'int'
        

Finally, here’s an example of a semantic error. Suppose we want to compute the average of 1 and 3, but we forget about the order of operations and write this:

1 + 3 / 2
        
2.5
        

When this expression is evaluated, it does not produce an error message, so there is no syntax error or runtime error. But the result is not the average of 1 and 3, so the program is not correct. This is a semantic error because the program runs but it doesn’t do what’s intended.

Glossary

variable: A name that refers to a value.

assignment statement: A statement that assigns a value to a variable.

state diagram: A graphical representation of a set of variables and the values they refer to.

keyword: A special word used to specify the structure of a program.

import statement: A statement that reads a module file and creates a module object.

module: A file that contains Python code, including function definitions and sometimes other statements.

dot operator: The operator, ., used to access a function in another module by specifying the module name followed by a dot and the function name.

statement: One or more lines of code that represent a command or action.

evaluate: Perform the operations in an expression in order to compute a value.

execute: Run a statement and do what it says.

argument: A value provided to a function when the function is called. Each argument is assigned to the corresponding parameter in the function.

comment: Text included in a program that provides information about the program but has no effect on its execution.

runtime error: An error that causes a program to display an error message and exit.

exception: An error that is detected while the program is running.

semantic error: An error that causes a program to do the wrong thing, but not to display an error message.

Exercises

Exercise

Repeating my advice from the previous chapter, whenever you learn a new feature, you should make errors on purpose to see what goes wrong.

  1. We’ve seen that n = 17 is legal. What about 17 = n?

  2. How about x = y = 1?

  3. In some languages every statement ends with a semicolon (;). What happens if you put a semicolon at the end of a Python statement?

  4. What if you put a period at the end of a statement?

  5. What happens if you spell the name of a module wrong and try to import maath?