Page 35 -
P. 35

12                                 Chapter 2. Variables, expressions and statements

                                  message     ’And now for something completely different’
                                        n     17
                                        pi    3.1415926535897932


                                               Figure 2.1: State diagram.


                  >>> 1,000,000
                  (1, 0, 0)
                  Well, that’s not what we expected at all! Python interprets 1,000,000 as a comma-
                  separated sequence of integers. This is the first example we have seen of a semantic error:
                  the code runs without producing an error message, but it doesn’t do the “right” thing.



                  2.2 Variables

                  One of the most powerful features of a programming language is the ability to manipulate
                  variables. A variable is a name that refers to a value.
                  An assignment statement creates new variables and gives them values:

                  >>> message =  'And now for something completely different  '
                  >>> n = 17
                  >>> pi = 3.1415926535897932
                  This example makes three assignments. The first assigns a string to a new variable named
                  message ; the second gives the integer 17 to n; the third assigns the (approximate) value of
                  π to pi.

                  A common way to represent variables on paper is to write the name with an arrow pointing
                  to the variable’s value. This kind of figure is called a state diagram because it shows what
                  state each of the variables is in (think of it as the variable’s state of mind). Figure 2.1 shows
                  the result of the previous example.

                  The type of a variable is the type of the value it refers to.
                  >>> type(message)
                  <type  'str '>
                  >>> type(n)
                  <type  'int '>
                  >>> type(pi)
                  <type  'float '>
                  Exercise 2.1. If you type an integer with a leading zero, you might get a confusing error:
                  >>> zipcode = 02492
                                     ^
                  SyntaxError: invalid token
                  Other numbers seem to work, but the results are bizarre:
                  >>> zipcode = 02132
                  >>> zipcode
                  1114
                  Can you figure out what is going on? Hint: display the values 01, 010, 0100 and 01000 .
   30   31   32   33   34   35   36   37   38   39   40