\chapter{Variables, expressions and statements}
\label{lec-variables}

\section{Values and types}

A \myidx{value} is one of the fundamental things---like a letter or a
number---that a program manipulates. The values we have seen so far
are 2 (the result when we added 1 + 1), and ``Hello, World!''. These
values belong to different \myidx{types}: 2 is an
\myidx{integer}, and ``Hello, World!'' is a \myidx{string}.
You (and the interpreter) can
identify strings because they are enclosed in quotation marks.

The print statement also works for integers.

\begin{pythonInteractive}
>>> print 4
4
\end{pythonInteractive}

If you are not sure what type a value has, the interpreter can tell
you.
% We don't talk about this being a function call because it isn't.

\begin{pythonInteractive}
>>> type("Hello, World!")
<type 'str'>
>>> type(17)
<type 'int'>
\end{pythonInteractive}

Strings belong to the type \myidx{str} and integers
belong to the type \myidx{int}. Less obviously, numbers with a
decimal point belong to a type called \myidx{float}, because these
numbers are represented in a format called \emph{floating-point}.

\begin{pythonInteractive}
>>> type(3.2)
<type 'float'>
\end{pythonInteractive}

What about values like ``17'' and ``3.2''? They look like numbers, but
they are in quotation marks like strings.

\begin{pythonInteractive}
>>> type("17")
<type 'str'>
>>> type("3.2")
<type 'str'>
\end{pythonInteractive}

\newpage
They're strings. Strings in Python can be enclosed in either single
quotes (') or double quotes (''):

\begin{pythonInteractive}
>>> type('This is a string.')
<type 'str'>
>>> type("And so is this.")
<type 'str'>
\end{pythonInteractive}

Double quoted strings can contain single quotes inside them, as in
\pythoninline{"What's your name?"}, and single quoted strings can have
double quotes inside them, as in \pythoninline{'The cat said
  "Meow!"'}. % 'The knights who say ``Ni!'''.

When you type a large integer, you might be tempted to use commas
between groups of three digits, as in 1,000,000. This is not a legal
integer in Python, but it is legal:

\begin{pythonInteractive}
>>> print 1,000,000
1 0 0
\end{pythonInteractive}

Well, that's not what we expected at all! Python interprets 1,000,000
as a list of three items to be printed. So remember not to put commas
in your integers.

\section{Variables}

One of the most powerful features of a programming language is the
ability to manipulate \myidx{variables}. A variable is a name that
refers to a value. The \myidx{assignment statement} creates new
variables and assigns them values:

\begin{pythonInteractive}
>>> message = "What's your name?"
>>> n = 17
>>> pi = 3.14159
\end{pythonInteractive}

This example makes three assignments. The first assigns the string
\pythoninline{"What's your name?"} to a new variable named
\pythoninline{message}. The second assigns the integer 17 to
\pythoninline{n}, and the third assigns the floating-point number
3.14159 to \pythoninline{pi}. The \myidx{assignment operator}, =,
should not be confused with an equals sign (even though it uses the
same character). Assignment operators link a \emph{name}, on the left
hand side of the operator, with a \emph{value}, on the right hand
side.  This is why you will get an error if you enter:

\begin{pythonInteractive}
>>> 17 = n
\end{pythonInteractive}


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 \myidx{state diagram} because it shows what state each of
the variables is in (think of it as the variable's state of
mind). This diagram shows the result of the assignment statements:

\includegraphics[scale=1]{figures/state2-fig} 

\newpage
The print statement also works with variables.

\begin{pythonInteractive}
>>> print message
What's your name?
>>> print n
17
>>> print pi
3.14159
\end{pythonInteractive}

In each case the result is the value of the variable. Variables also
have types; again, we can ask the interpreter what they are.

\begin{pythonInteractive}
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
\end{pythonInteractive}

The type of a variable is the type (or kind) of value it refers to.

\section{Variable names and keywords}

Programmers generally choose names for their variables that are
meaningful---they document what the variable is used for.
\myidx{Variable names} can be arbitrarily long. They can contain both
letters and numbers, but they have to begin with a letter. Although it
is legal to use uppercase letters, by convention we don't. If you do,
remember that case matters. \pythoninline{Bruce} and
\pythoninline{bruce} are different variables.  The underscore
character (\_) can appear in a name. It is often used in names with
multiple words, such as \pythoninline{my\_name} or
\pythoninline{price\_of\_tea\_in\_china}. If you give a variable an
illegal name, you get a syntax error:

\begin{pythonInteractive}
>>> 76trombones = "big parade"
SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = "COMP150"
SyntaxError: invalid syntax
\end{pythonInteractive} % $ (keep emacs happy)

\pythoninline{76trombones} is illegal because it does not begin with a
letter. \pythoninline{more\$} is illegal because it contains an
illegal character, the dollar sign.  But what's wrong with
\pythoninline{class}? It turns out that class is one of the Python
\myidx{keywords}. Keywords define the language's rules and structure,
and they cannot be used as variable names. Python has thirty-one
keywords:
\begin{verbatim}
   and       del       from      not       while
   as        elif      global    or        with
   assert    else      if        pass      yield
   break     except    import    print
   class     exec      in        raise
   continue  finally   is        return
   def       for       lambda    try
\end{verbatim}
You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don't know why, see if it is
on this list.

\section{Statements}

A \myidx{statement} is an instruction that the Python interpreter can
execute. We have seen two kinds of statements: print and assignment. 
When you type a statement on the command line, Python executes it and
displays the result, if there is one. The result of a print statement
is a value. Assignment statements don't produce a visible result. A script
usually contains a sequence of statements. If there is more than one
statement, the results appear one at a time as the statements execute. 
For example, the script

\begin{python}
print 1
x = 2
print x
\end{python}

produces the output

\begin{pythonOutput}
1
2
\end{pythonOutput}

Again, the assignment statement produces no output.

\section{Evaluating expressions}

An \myidx{expression} is a combination of values, variables, and
operators. If you type an expression on the command line, the
interpreter \myidx{evaluates} it and displays the result:

\begin{pythonInteractive}
>>> 1 + 1
2
\end{pythonInteractive}

The \emph{evaluation of an expression} produces a value, which is why
expressions can appear on the right hand side of assignment
statements. A value all by itself is a simple expression, and so is a
variable.

\begin{pythonInteractive}
>>> 17
17
>>> x
2
\end{pythonInteractive}

Confusingly, evaluating an expression is not quite the same thing as
printing a value.

\begin{pythonInteractive}
>>> message = "What's your name?"
>>> message
"What's your name?"
>>> print message
What's your name?
\end{pythonInteractive}

When the Python shell displays the value of an expression, it uses the
same format you would use to enter a value. In the case of strings,
that means that it includes the quotation marks. But the print
statement prints the value of the expression, which in this case is
the contents of the string. In a script, an expression all by itself
is a legal statement, but it doesn't do anything. The script

\begin{python}
17
3.2
"Hello, World!"
1 + 1
\end{python}

produces no output at all. How would you change the script to display
the values of these four expressions?

\section{Operators and operands}

\myidx{Operators} are special symbols that represent computations
like addition and multiplication. The values the operator uses are
called \myidx{operands}. The following are all legal Python
expressions whose meaning is more or less clear:

\begin{python}
20 + 32   
hour - 1   
hour * 60 + minute   
minute / 60   
5 ** 2   
(5 + 9) * (15 - 7)
\end{python}

The symbols \pythoninline{+}, \pythoninline{-}, \pythoninline{*},
\pythoninline{/}, have the usual mathematical meanings. The symbol,
\pythoninline{**}, is the exponentiation operator. The statement,
\pythoninline{5 ** 2}, means 5 to the power of 2, or 5 squared in this
case. Python also uses parentheses for grouping, so we can force
operations to be done in a certain order just like we can in
mathematics. 

When a variable name appears in the place of an operand, it is
replaced with its value before the operation is performed. Addition,
subtraction, multiplication, and exponentiation all do what you
expect, but you might be surprised by division. The following
operation has an unexpected result:

\begin{pythonInteractive}
>>> minute = 59
>>> minute / 60
0
\end{pythonInteractive}

The value of \pythoninline{minute} is \pythoninline{59}, and
\pythoninline{59} divided by \pythoninline{60} is
\pythoninline{0.98333}, not \pythoninline{0}. The
reason for the discrepancy is that Python is performing
\myidx{integer division}\footnote{In Python 3000, floating point
division is used}. When both of the operands are integers, the result
must also be an integer, and by convention, integer division always
rounds \emph{down}, even in cases like this where the next integer is
very close. A possible solution to this problem is to calculate a
percentage rather than a fraction:

\begin{pythonInteractive}
>>> minute * 100 / 60
98
\end{pythonInteractive}

Again the result is rounded down, but at least now the answer is
approximately correct. Another alternative is to use floating-point
division. We'll see in Lecture \ref{sec-type-conversion}
% TODO: should this be lecture num instead of section num?
how to convert integer values and variables to floating-point values.

\section{The modulus operator}

The \myidx{modulus operator} works on integers (and integer
expressions) and floats and yields the remainder when the first operand is
divided by the second. In Python, the modulus operator is a percent
sign (\pythoninline{\%}). The syntax is the same as for other operators:

\newpage
\begin{pythonInteractive}
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
\end{pythonInteractive}

So \pythoninline{7} divided by \pythoninline{3} is \pythoninline{2}
with \pythoninline{1} left over. The modulus operator turns out to be
surprisingly useful. For example, you can check whether one number is
divisible by another---if \pythoninline{x \% y} is zero, then
\pythoninline{x} is divisible by \pythoninline{y}. Also, you can
extract the right-most digit or digits from a number. For example,
\pythoninline{x \% 10} yields the right-most digit of \pythoninline{x}
(in base 10). Similarly \pythoninline{x \% 100} yields the last two
digits. 

\section{Order of operations}

When more than one operator appears in an expression, the order of
evaluation depends on the \myidx{rules of precedence}. Python
follows the same precedence rules for its mathematical operators that
mathematics does. The acronym PEMDAS is a useful way to remember the
order of operations:
\begin{enumerate}
\item \textbf{P}arentheses have the highest precedence and can be used
to force an expression to evaluate in the order you want. Since
expressions in parentheses are evaluated first, \pythoninline{2*(3-1)}
is \pythoninline{4}, and \pythoninline{(1+1)**(5-2)} is 8. You can
also use parentheses to make an expression easier to read, as in
\pythoninline{(minute*100)/60}, even though it doesn't change the
result. 
\item \textbf{E}xponentiation has the next highest precedence, so
\pythoninline{2**1+1} is \pythoninline{3} and not \pythoninline{4},
and \pythoninline{3*1**3} is \pythoninline{3} and not
\pythoninline{27}. \item \textbf{M}ultiplication and \textbf{D}ivision
have the same precedence, which is higher than \textbf{A}ddition and
\textbf{S}ubtraction, which also have the same precedence. So
\pythoninline{2*3-1} yields \pythoninline{5} rather than
\pythoninline{4}, and \pythoninline{2/3-1} is \pythoninline{-1}, not
\pythoninline{1} (remember that in integer division,
\pythoninline{2/3=0}).
\begin{sloppypar}  
\item Operators with the same precedence are evaluated from left to
right. So in the expression \pythoninline{minute*100/60}, the
multiplication happens first, yielding \pythoninline{5900/60}, which
in turn yields \pythoninline{98}. If the operations had been evaluated
from right to left, the result would have been \pythoninline{59*1},
which is \pythoninline{59}, which is wrong.
\end{sloppypar}
\end{enumerate}
If in doubt, use parentheses.

\section{Operations on strings}

In general, you cannot perform mathematical operations on strings,
even if the strings look like numbers. The following are illegal
(assuming that message has type string):

\begin{python}
message - 1
"Hello" / 123   
message * "Hello"   
"15" + 2
\end{python}

Interestingly, the + operator does work with strings, although it does
not do exactly what you might expect. For strings, the + operator
represents \myidx{concatenation}, which means joining the two
operands by linking them end-to-end. For example:

\begin{python}
fruit = "banana"
baked_good = " nut bread"
print fruit + baked_good
\end{python}

The output of this program is \pythoninline{banana nut bread}. The
space before the 
word nut is part of the string, and is necessary to produce the space
between the concatenated strings. The * operator also works on
strings; it performs repetition. For example, \pythoninline{'Fun'*3}
is \pythoninline{'FunFunFun'}. 
One of the operands has to be a string; the other has to be an
integer. On one hand, this interpretation of + and * makes sense by
analogy with addition and multiplication. Just as \pythoninline{4*3}
is equivalent to \pythoninline{4+4+4}, we expect
\pythoninline{`Fun'*3} to be the same as
\pythoninline{`Fun'+'Fun'+'Fun'},
and it is. On the other hand, there is a significant way in which
string concatenation and repetition are different from integer
addition and multiplication. Can you think of a property that addition
and multiplication have that string concatenation and repetition do
not?


\section{Glossary}
\begin{description}
\item[value:]A number or string (or other thing to be named later)
  that can be stored in a variable or computed in an expression.
\item[type:]A set of values. The type of a value determines how it can
  be used in expressions. So far, the types you have seen are integers
  (type int), floating-point numbers (type float), and strings (type
  string).
\item[type function:]A function which returns the type of the given
  argument, for example:
\begin{python}
>>> type("Hello, world!")
<type 'str'>
>>> type(17)
<type 'int'>
\end{python}
\item[int:]A Python data type that holds positive and negative whole
  numbers.
\item[str:]A Python data type that holds a string of characters.
\item[float:]A Python data type which stores \emph{floating-point}
  numbers. Floating-point numbers are stored internally in two parts:
  a \emph{base} and an \emph{exponent}. When printed in the standard
  format, they look like decimal numbers. Beware of rounding errors
  when you use floats, and remember that they are only approximate
  values.
\item[variable:]A name that refers to a value.
\item[assignment statement:]A statement that assigns a value to a name
  (variable). To the left of the assignment operator, =, is a name. To
  the right of the assignment operator is an expression which is
  evaluated by the Python interpreter and then assigned to the
  name. The difference between the left and right hand sides of the
  assignment statement is often confusing to new programmers. In the
  following assignment:

\begin{python}
n = n + 1
\end{python}

  n plays a very different role on each side of the =. On the right it
  is a \emph{value} and makes up part of the \emph{expression} which
  will be evaluated by the Python interpreter before assigning it to
  the name on the left.
\item[assignment operator:]= is Python's assignment operator, which
  should not be confused with the mathematical comparison operator
  using the same symbol.
\item[state diagram:]A graphical representation of a set of variables
  and the values to which they refer.
\item[variable name:]A name given to a variable. Variable names in
  Python consist of a sequence of letters (a..z, A..Z, and \_) and
  digits (0..9) that begins with a letter. In best programming
  practice, variable names should be chosen so that they describe
  their use in the program, making the program \emph{self documenting}.
\item[keyword:]A reserved word that is used by the compiler to parse a
  program; you cannot use keywords like \pythoninline{if},
\pythoninline{def}, and \pythoninline{while} as variable
  names.
\item[statement:]An instruction that the Python interpreter can
  execute. Examples of statements include the assignment statement and
  the print statement.
\item[expression:]A combination of variables, operators, and values
  that represents a single result value.
\item[evaluate:]To simplify an expression by performing the operations
  in order to yield a single value.
\item[operator:]A special symbol that represents a simple computation
  like addition, multiplication, or string concatenation.
\item[operand:]One of the values on which an operator operates.
\item[modulus operator:]An operator, denoted with a percent sign (\%),
  that works on integers and floats and yields the remainder when one number is
  divided by another.
\item[integer division:]An operation that divides one integer by
  another and yields an integer. Integer division yields only the
  whole number of times that the numerator is divisible by the
  denominator and discards any remainder.
\item[rules of precedence:]The set of rules governing the order in
  which expressions involving multiple operators and operands are
  evaluated.
\item[concatenate:]To join two operands end-to-end.
\item[composition:]The ability to combine simple expressions and
  statements into compound statements and expressions in order to
  represent complex computations concisely.

\end{description}

\section{Laboratory exercises}

\begin{enumerate}

\item Create a Folder in your Home Directory called \myurl{Lab2} to
  store the files you create during this lab.

\item Record what happens when you print an assignment
statement:
 
\begin{pythonInteractive}
>>> print n = 7
\end{pythonInteractive}

\begin{answerspace}

zend
\end{answerspace}

How about this?

\begin{pythonInteractive}
>>> print 7 + 5
\end{pythonInteractive}

\begin{answerspace}

zend
\end{answerspace}

Or this?

\begin{pythonInteractive}
>>> print 5.2, "this", 4 - 2, "that", 5/2.0 
\end{pythonInteractive}

\begin{answerspace}

zend
\end{answerspace}

Can you think a general rule for what can follow the print
statement?

\begin{answerspace}


zend
\end{answerspace}

\item \label{ex-chap2-jack} Take the sentence: \emph{All work and no play makes Jack a dull
    boy.}  Show how you would use the interpreter to store each word
  in a separate variable, then print out the sentence on one line
  using print.
\begin{answerspace}











zend
\end{answerspace}
Check that your answer is correct by entering it into the interpreter.

\item Repeat exercise \ref{ex-chap2-jack}, this time using a script.
\item Add parentheses to the expression \pythoninline{6*1-2} to change its value
from \pythoninline{4} to \pythoninline{-6}.
\begin{answerspace}

zend
\end{answerspace}

\item Try to evaluate the following numerical expressions in your
  head, and put the answer beside each one, then use the Python
  interpreter to check your results:
\begin{pythonInteractive}
>>> 5 % 2
>>> 9 % 5
>>> 15 % 12
>>> 12 % 15
>>> 6 % 6
>>> 0 % 7
>>> 7 % 0
\end{pythonInteractive}

What happened with the last example? Why? If you were able to
correctly anticipate the computer's response in all but the last
one, it is time to move on. If not, take time now to make up
examples of your own. Explore the modulus operator until you are
confident you understand how it works.


\item Start the Python interpreter and enter \pythoninline{bruce~+~4}
  at the prompt. This will give you an error:

\begin{pythonOutput}
NameError: name 'bruce' is not defined
\end{pythonOutput}

Assign a value to \pythoninline{bruce} so that
\pythoninline{bruce~+~4} evaluates to \pythoninline{10}.


\item Since this lab is reasonably short we have provided you with a
  little game to play that can help you practice thinking in a problem
  solving way.  Look on the whiteboard for instructions on how to
  begin the game.  Work your way through the first three levels.
  % 1: straight, 2: turn, 3: jump

\end{enumerate}

\submitreminder
