How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Variables, expressions, and statements

= Variables, expressions and statements =

Values and types
A 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 &quot;Hello, World!&quot;.

These values belong to different types: 2 is an integer, and &quot;Hello, World!&quot; is a string, so-called because it contains a string 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 &quot;17&quot; and &quot;3.2&quot;? They look like numbers, but they are in quotation marks like strings.

They're strings.

Strings in Python can be enclosed in either single quotes (') or double quotes (&quot;):

Double quoted strings can contain single quotes inside them, as in &quot;Bruce's beard&quot;, and single quoted strings can have double quotes inside them, as in <tt>'The knights who say &quot;Ni!&quot;'</tt>.

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

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

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.

The assignment statement creates new variables and gives them values:

This example makes three assignments. The first assigns the string <tt>&quot;What's up, Doc?&quot;</tt> to a new variable named <tt>message</tt>. The second gives the integer <tt>17</tt> to <tt>n</tt>, and the third gives the floating-point number <tt>3.14159</tt> to <tt>pi</tt>.

The assignment operator, <tt>=</tt>, should not be confused with an equals sign (even though it uses the same character). Assignment operators link a name, on the left hand side of the operator, with a value, on the right hand side. This is why you will get an error if you enter:

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). This diagram shows the result of the assignment statements:

The print statement also works with variables.

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

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

Variable names and keywords
Programmers generally choose names for their variables that are meaningful ---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. Although it is legal to use uppercase letters, by convention we don't. If you do, remember that case matters. <tt>Bruce</tt> and <tt>bruce</tt> are different variables.

The underscore character ( <tt>_</tt>) can appear in a name. It is often used in names with multiple words, such as <tt>my_name</tt> or <tt>price_of_tea_in_china</tt>.

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, the dollar sign. But what's wrong with <tt>class</tt>?

It turns out that <tt>class</tt> is one of the Python keywords. Keywords define the language's rules and structure, and they cannot be used as variable names.

Python has thirty-one keywords:

1. <tt>and</tt> / 2. <tt>as</tt> / 3. <tt>assert</tt> / 4. <tt>break</tt> / 5. <tt>class</tt> / 6. <tt>continue</tt> / 7. <tt>def</tt> / 8. <tt>del</tt> / 9. <tt>elif</tt> / 10. <tt>else</tt> / 11. <tt>except</tt> / 12. <tt>exec</tt> / 13. <tt>finally</tt> / 14. <tt>for</tt> / 15. <tt>from</tt> / 16. <tt>global</tt> / 17. <tt>if</tt> / 18. <tt>import</tt> / 19. <tt>in</tt> / 20. <tt>is</tt> / 21. <tt>lambda</tt> / 22. <tt>not</tt> / 23. <tt>or</tt> / 24. <tt>pass</tt> / 25. <tt>print</tt> / 26. <tt>raise</tt> / 27. <tt>return</tt> / 28. <tt>try</tt> / 29. <tt>while</tt> / 30. <tt>with</tt> / 31. <tt>yield</tt> /

You might want to keep this list handy. If the interpreter complains about one of your variable names and you don't know why, check if your variable names are on this list.

Statements
A 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 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

produces the output:

1 2 Again, the assignment statement produces no output.

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

The 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.

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

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

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

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

The following are all legal Python expressions whose meaning is more or less clear:

20+32  hour-1   hour*60+minute   minute/60   5**2   (5+9)*(15-7) The symbols <tt>+</tt>, <tt>-</tt>, and <tt>/</tt>, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (<tt>*</tt>) is the symbol for multiplication, and <tt>**</tt> is the symbol for exponentiation.

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:

The value of <tt>minute</tt> is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Python is performing integer division.

When both of the operands are integers, the result must also be an integer, and by convention, integer division always rounds 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:

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 the chapter 4 how to convert integer values and variables to floating-point values.

Order of operations
When more than one operator appears in an expression, the order of evaluation depends on the 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:

<ol> <li>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, <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 though it doesn't change the result.</li> <li>E xponentiation has the next highest precedence, so <tt>2**1+1</tt> is 3 and not 4, and <tt>3*1**3</tt> is 3 and not 27.</li> <li>M ultiplication and D ivision have the same precedence, which is higher than A ddition and S ubtraction, which also have the same precedence. So <tt>2*3-1</tt> yields 5 rather than 4, and <tt>2/3-1</tt> is -1, not 1 (remember that in integer division, 2/3=0).</li> <li>Operators with the same precedence are evaluated from left to right. So in the expression <tt>minute*100/60</tt>, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been <tt>59*1</tt>, which is 59, which is wrong.</li></ol>

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 <tt>message</tt> has type string):

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

The output of this program is <tt>banana nut bread</tt>. The space before the word <tt>nut</tt> is part of the string, and is necessary to produce the space between the concatenated strings.

The <tt>*</tt> operator also works on strings; it performs repetition. For example, <tt>'Fun'*3</tt> is <tt>'FunFunFun'</tt>. One of the operands has to be a string; the other has to be an integer.

On one hand, this interpretation 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 <tt>&quot;Fun&quot;*3</tt> to be the same as <tt>&quot;Fun&quot;+&quot;Fun&quot;+&quot;Fun&quot;</tt>, 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?

Input
There are two built-in functions in Python for getting keyboard input:

A sample run of this script would look something like this:

$ python tryinput.py Please enter your name: Arthur, King of the Britons Arthur, King of the Britons Enter a numerical expression: 7 * 3 21 Each of these functions allows a prompt to be given to the function between the parentheses.

Composition
So far, we have looked at the elements of a program --- variables, expressions, and statements --- in isolation, without talking about how to combine them.

One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:

In reality, the addition has to happen before the printing, so the actions aren't actually happening at the same time. The point is that any expression involving numbers, strings, and variables can be used inside a print statement. You've already seen an example of this:

You can also put arbitrary expressions on the right-hand side of an assignment statement:

This ability may not seem impressive now, but you will see other examples where composition makes it possible to express complex computations neatly and concisely.

Warning: There are limits on where you can use certain expressions. For example, the left-hand side of an assignment statement has to be a variable name, not an expression. So, the following is illegal: <tt>minute+1 = hour</tt>.

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 are marked with the <tt>#</tt> 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 <tt>#</tt> to the end of the line is ignored --- it has no effect on the program. The message is intended for the programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising behavior of integer division.

Exercises
<ol> <li> Record what happens when you print an assignment statement:

How about this?

Or this?

Can you think a general rule for what can follow the <tt>print</tt> statement? What does the <tt>print</tt> statement return?</li> <li>Take the sentence: All work and no play makes Jack a dull boy. Store each word in a separate variable, then print out the sentence on one line using print.</li> <li>Add parenthesis to the expression <tt>6 * 1 - 2</tt> to change its value from 4 to -6.</li> <li>Place a comment before a line of code that previously worked, and record what happens when you rerun the program.</li> <li> The difference between <tt>input</tt> and <tt>raw_input</tt> is that <tt>input</tt> evaluates the input string and <tt>raw_input</tt> does not. Try the following in the interpreter and record what happens:

What happens if you try the example above without the quotation marks?

Describe and explain each result.</li> <li> Start the Python interpreter and enter <tt>bruce + 4</tt> at the prompt. This will give you an error:

Assign a value to <tt>bruce</tt> so that <tt>bruce + 4</tt> evaluates to <tt>10</tt>.</li> <li> Write a program (Python script) named <tt>madlib.py</tt>, which asks the user to enter a series of nouns, verbs, adjectives, adverbs, plural nouns, past tense verbs, etc., and then generates a paragraph which is syntactically correct but semantically ridiculous (see [http://madlibs.org http://madlibs.org]_ for examples). </li></ol>