Think Python/Variables, expressions and statements

Values and types
A value is one of the basic things a program works with, like a letter or a number. The values we have seen so far are 1, 2, and.

These values belong to different types: 2 is an integer, and  is a string, so-called because it contains a &#X201C;string&#X201D; of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

The print statement also works for integers.

If you are not sure what type a value has, the interpreter can tell you.

Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point belong to a type called float, because these numbers are represented in a format called floating-point.

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

They're strings.

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:

Well, that&#X2019;s not what we expected at all! Python interprets 1,000,000 as a comma-separated sequence of integers, which it prints with spaces between.

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 &#X201C;right&#X201D; thing.

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:

This example makes three assignments. The first assigns a string to a new variable named <TT>message</TT>; the second gives the integer <TT>17</TT> to <TT>n</TT>; the third assigns the (approximate) value of &#X3C0; to <TT>pi</TT>.

A common way to represent variables on paper is to write the name with an arrow pointing to the variable&#X2019;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&#X2019;s state of mind). This diagram shows the result of the previous example:

To display the value of a variable, you can use a print statement:

The type of a variable is the type of the value it refers to.

Exercise 1
If you type an integer with a leading zero, you might get a confusing error:

Other numbers seem to work, but the results are bizarre:

Can you figure out what is going on? Hint: print the values,  ,   and.

Variable names and keywords
Programmers generally choose names for their variables that are meaningful&#X2014;they document what the variable is used for.

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter (you'll see why later).

The underscore character can appear in a name. It is often used in names with multiple words, such as  or.

If you give a variable an illegal name, you get a syntax error: <TT>76trombones</TT> is illegal because it does not begin with a letter. <TT>more@</TT> is illegal because it contains an illegal character, <TT>@</TT>. But what's wrong with <TT>class</TT>?

It turns out that <TT>class</TT> is one of Python's keywords. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names.

Python has 31 keywords:

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.

If you write your code in a text editor that understands Python, you may find that it makes it easy for you to spot such keyword clashes by displaying keywords in a different color to ordinary variables. This feature is called syntax highlighting, and most programmers find it indispensable. This book uses syntax highlighting for its example code, so in the following example:

you can see that  has been recognized as a keyword and not as an ordinary variable, since it is colored green.

Statements
A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.

When you type a statement in interactive mode, the interpreter executes it and displays the result, if there is one.

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 produces the output The assignment statement produces no output.

Operators and operands
Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

The operators <TT>+</TT>, <TT>-</TT>, <TT>*</TT>, <TT>/</TT> and <TT>**</TT> perform addition, subtraction, multiplication, division and exponentiation, as in the following examples: In some other languages,  is used for exponentiation, but in Python it is a bitwise operator called XOR. I won&#X2019;t cover bitwise operators in this book, but you can read about them at <TT>wiki.python.org/moin/BitwiseOperators</TT>.

The division operator might not do what you expect: The value of <TT>minute</TT> is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing floor division.

When both of the operands are integers, the result is also an integer; floor division chops off the fraction part, so in this example it rounds down to zero.

If either of the operands is a floating-point number, Python performs floating-point division, and the result is a <TT>float</TT>:

Expressions
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions (assuming that the variable <TT>x</TT> has been assigned a value):

If you type an expression in interactive mode, the interpreter evaluates it and displays the result: But in a script, an expression all by itself doesn&#X2019;t do anything! This is a common source of confusion for beginners.

Exercise 2
Type the following statements in the Python interpreter to see what they do:

Now put the same statements into a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again.

Order of operations
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:


 * Parentheses 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, <TT>2 * (3-1)</TT> is 4, and <TT>(1+1)**(5-2)</TT> is 8. You can also use parentheses to make an expression easier to read, as in <TT>(minute * 100) / 60</TT>, even if it doesn't change the result.
 * Exponentiation has the next highest precedence, so <TT>2**1+1</TT> is 3, not 4, and <TT>3*1**3</TT> is 3, not 27.
 * Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So <TT>2*3-1</TT> is 5, not 4, and <TT>6+4/2</TT> is 8, not 5.
 * Operators with the same precedence are evaluated from left to right. So in the expression <TT>degrees / 2 * pi</TT>, the division happens first and the result is multiplied by <TT>pi</TT>. To divide by 2 &#X3C0;, you can reorder the operands or use parentheses.

String operations
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal: The <TT>+</TT> operator works with strings, but it might not do what you expect: it performs concatenation, which means joining the strings by linking them end-to-end. For example:

The output of this program is <TT>throatwarbler</TT>.

The <TT>*</TT> operator also works on strings; it performs repetition. For example, <TT>&#X2019;Spam&#X2019;*3</TT> is. If one of the operands is a string, the other has to be an integer.

This use of <TT>+</TT> and <TT>*</TT> makes sense by analogy with addition and multiplication. Just as <TT>4*3</TT> is equivalent to <TT>4+4+4</TT>, we expect  to be the same as, 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 has that string concatenation does not?

Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.

For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the  symbol:

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

Everything from the  to the end of the line is ignored&#X2014;it has no effect on the program.

Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is much more useful to explain why.

This comment is redundant with the code and useless:

This comment contains useful information that is not in the code:

Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.

Debugging
At this point the syntax error you are most likely to make is an illegal variable name, like <TT>class</TT> and <TT>yield</TT>, which are keywords, or  and , which contain illegal characters.

If you put a space in a variable name, Python thinks it is two operands without an operator: For syntax errors, the error messages don&#X2019;t help much. The most common messages are <TT>SyntaxError: invalid syntax</TT> and <TT>SyntaxError: invalid token</TT>, neither of which is very informative.

The runtime error you are most likely to make is a &#X201C;use before def;&#X201D; that is, trying to use a variable before you have assigned a value. This can happen if you spell a variable name wrong: Variables names are case sensitive, so <TT>LaTeX</TT> is not the same as <TT>latex</TT>.

At this point the most likely cause of a semantic error is the order of operations. For example, to evaluate 1/2 &#X3C0;, you might be tempted to write But the division happens first, so you would get &#X3C0; / 2, which is not the same thing! There is no way for Python to know what you meant to write, so in this case you don&#X2019;t get an error message; you just get the wrong answer.

Glossary
<DL CLASS="description"><DT CLASS="dt-description">value:</DT><DD CLASS="dd-description"> One of the basic units of data, like a number or string, that a program manipulates. </DD><DT CLASS="dt-description">type:</DT><DD CLASS="dd-description"> A category of values. The types we have seen so far are integers (type <TT>int</TT>), floating-point numbers (type <TT>float</TT>), and strings (type <TT>str</TT>). </DD><DT CLASS="dt-description">integer:</DT><DD CLASS="dd-description"> A type that represents whole numbers. </DD><DT CLASS="dt-description">floating-point:</DT><DD CLASS="dd-description"> A type that represents numbers with fractional parts. </DD><DT CLASS="dt-description">string:</DT><DD CLASS="dd-description"> A type that represents sequences of characters. </DD><DT CLASS="dt-description">variable:</DT><DD CLASS="dd-description"> A name that refers to a value. </DD><DT CLASS="dt-description">statement:</DT><DD CLASS="dd-description"> A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements. </DD><DT CLASS="dt-description">assignment:</DT><DD CLASS="dd-description"> A statement that assigns a value to a variable. </DD><DT CLASS="dt-description">state diagram:</DT><DD CLASS="dd-description"> A graphical representation of a set of variables and the values they refer to. </DD><DT CLASS="dt-description">keyword:</DT><DD CLASS="dd-description"> A reserved word that is used by the compiler to parse a program; you cannot use keywords like <TT>if</TT>, <TT>def</TT>, and <TT>while</TT> as variable names. </DD><DT CLASS="dt-description">operator:</DT><DD CLASS="dd-description"> A special symbol that represents a simple computation like addition, multiplication, or string concatenation. </DD><DT CLASS="dt-description">operand:</DT><DD CLASS="dd-description"> One of the values on which an operator operates. </DD><DT CLASS="dt-description">floor division:</DT><DD CLASS="dd-description"> The operation that divides two numbers and chops off the fraction part. </DD><DT CLASS="dt-description">expression:</DT><DD CLASS="dd-description"> A combination of variables, operators, and values that represents a single result value. </DD><DT CLASS="dt-description">evaluate:</DT><DD CLASS="dd-description"> To simplify an expression by performing the operations in order to yield a single value.</DD><DT CLASS="dt-description">rules of precedence:</DT><DD CLASS="dd-description"> The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.

</DD><DT CLASS="dt-description">concatenate:</DT><DD CLASS="dd-description"> To join two operands end-to-end. </DD><DT CLASS="dt-description">comment:</DT><DD CLASS="dd-description"> Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program. </DD></DL>

Exercise 3
Assume that we execute the following assignment statements:

For each of the following expressions, write the value of the expression and the type (of the value of the expression).

Use the Python interpreter to check your answers.

Exercise 4
Practice using the Python interpreter as a calculator:


 * The volume of a sphere with radius $$r$$ is 4/3 &#X3C0; $$r^3$$. What is the volume of a sphere with radius 5? Hint: 392.6 is wrong!


 * Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?


 * If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?