forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbook003.html
More file actions
459 lines (457 loc) · 37.6 KB
/
book003.html
File metadata and controls
459 lines (457 loc) · 37.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="hevea 2.09" />
<link rel="stylesheet" type="text/css" href="book.css" />
<title>Variables, expressions, and statements</title>
</head>
<body>
<a href="book002.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book004.html"><img src="next_motif.gif" alt="Next" /></a>
<hr />
<h1 class="chapter" id="sec17"><span class="c006">Chapter 2  Variables, expressions, and statements</span></h1>
<span class="c005">
</span><h2 class="section" id="sec18"><span class="c006">2.1  Values and types</span></h2>
<p><span class="c005">
</span><a id="hevea_default32"></a><span class="c005">
</span><a id="hevea_default33"></a><span class="c005">
</span><a id="hevea_default34"></a></p><p><span class="c006">A <span class="c009">value</span> is one of the basic things a program works with,
like a letter or a
number. The values we have seen so far
are <span class="c001">1</span>, <span class="c001">2</span>, and
<code>'Hello, World!'</code></span></p><p><span class="c006">These values belong to different <span class="c009">types</span>:
<span class="c001">2</span> is an integer, and <code>'Hello, World!'</code> is a <span class="c009">string</span>,
so called because it contains a “string” of letters.
You (and the interpreter) can identify
strings because they are enclosed in quotation marks.</span></p><p><a id="hevea_default35"></a></p><p><span class="c006">The <span class="c001">print</span> statement also works for integers. We use the
<span class="c001">python</span> command to start the interpreter.</span></p><pre class="verbatim"><span class="c004">python
>>> print 4
4
</span></pre><p><span class="c006">If you are not sure what type a value has, the interpreter can tell you.</span></p><pre class="verbatim"><span class="c004">>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
</span></pre><p><span class="c006">Not surprisingly, strings belong to the type <span class="c001">str</span> and
integers belong to the type <span class="c001">int</span>. Less obviously, numbers
with a decimal point belong to a type called <span class="c001">float</span>,
because these numbers are represented in a
format called <span class="c009">floating point</span>.</span></p><p><a id="hevea_default36"></a><span class="c005">
</span><a id="hevea_default37"></a><span class="c005">
</span><a id="hevea_default38"></a><span class="c005">
</span><a id="hevea_default39"></a><span class="c005">
</span><a id="hevea_default40"></a><span class="c005">
</span><a id="hevea_default41"></a><span class="c005">
</span><a id="hevea_default42"></a></p><pre class="verbatim"><span class="c004">>>> type(3.2)
<type 'float'>
</span></pre><p><span class="c006">What about values like <code>'17'</code> and <code>'3.2'</code>?
They look like numbers, but they are in quotation marks like
strings.</span></p><p><a id="hevea_default43"></a></p><pre class="verbatim"><span class="c004">>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
</span></pre><p><span class="c006">They’re strings.</span></p><p><span class="c006">When you type a large integer, you might be tempted to use commas
between groups of three digits, as in <span class="c001">1,000,000</span>. This is not a
legal integer in Python, but it is legal:</span></p><pre class="verbatim"><span class="c004">>>> print 1,000,000
1 0 0
</span></pre><p><span class="c006">Well, that’s not what we expected at all! Python interprets <span class="c001">1,000,000</span> as a comma-separated sequence of integers, which it
prints with spaces between.</span></p><p><a id="hevea_default44"></a><span class="c005">
</span><a id="hevea_default45"></a><span class="c005">
</span><a id="hevea_default46"></a></p><p><span class="c006">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.</span></p><span class="c005">
</span><h2 class="section" id="sec19"><span class="c006">2.2  Variables</span></h2>
<p><span class="c005">
</span><a id="hevea_default47"></a><span class="c005">
</span><a id="hevea_default48"></a><span class="c005">
</span><a id="hevea_default49"></a></p><p><span class="c006">One of the most powerful features of a programming language is the
ability to manipulate <span class="c009">variables</span>. A variable is a name that
refers to a value.</span></p><p><span class="c006">An <span class="c009">assignment statement</span> creates new variables and gives
them values:</span></p><pre class="verbatim"><span class="c004">>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
</span></pre><p><span class="c006">This example makes three assignments. The first assigns a string
to a new variable named <span class="c001">message</span>;
the second assigns the integer <span class="c001">17</span> to <span class="c001">n</span>; the third
assigns the (approximate) value of π to <span class="c001">pi</span>.</span></p><p><span class="c006">To display the value of a variable, you can use a print statement:</span></p><pre class="verbatim"><span class="c004">>>> print n
17
>>> print pi
3.14159265359
</span></pre><p><span class="c006">The type of a variable is the type of the value it refers to.</span></p><pre class="verbatim"><span class="c004">>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
</span></pre><span class="c005">
</span><h2 class="section" id="sec20"><span class="c006">2.3  Variable names and keywords</span></h2>
<p><span class="c005">
</span><a id="hevea_default50"></a></p><p><span class="c006">Programmers generally choose names for their variables that
are meaningful and document what the variable is used for.</span></p><p><span class="c006">Variable names can be arbitrarily long. They can contain
both letters and numbers, but they cannot start with a number.
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).</span></p><p><span class="c006">The underscore character (<code>_</code>) can appear in a name.
It is often used in names with multiple words, such as
<code>my_name</code> or <code>airspeed_of_unladen_swallow</code>.
Variable names can start with an underscore character, but
we generally avoid doing this unless we are writing library
code for others to use.</span></p><p><a id="hevea_default51"></a></p><p><span class="c006">If you give a variable an illegal name, you get a syntax error:</span></p><pre class="verbatim"><span class="c004">>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
</span></pre><p><span class="c006"><span class="c001">76trombones</span> is illegal because it begins with a number.
<span class="c001">more@</span> is illegal because it contains an illegal character, <span class="c001">@</span>. But what’s wrong with <span class="c001">class</span>?</span></p><p><span class="c006">It turns out that <span class="c001">class</span> is one of Python’s <span class="c009">keywords</span>. The
interpreter uses keywords to recognize the structure of the program,
and they cannot be used as variable names.</span></p><p><a id="hevea_default52"></a></p><p><span class="c006">Python reserves 31 keywords</span><sup><a id="text3" href="#note3"><span class="c006">1</span></a></sup><span class="c006"> for its use:</span></p><pre class="verbatim"><span class="c004">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
</span></pre><p><span class="c006">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.</span></p><span class="c005">
</span><h2 class="section" id="sec21"><span class="c006">2.4  Statements</span></h2>
<p><span class="c006">A <span class="c009">statement</span> is a unit of code that the Python interpreter can
execute. We have seen two kinds of statements: print
and assignment.</span></p><p><a id="hevea_default53"></a><span class="c005">
</span><a id="hevea_default54"></a><span class="c005">
</span><a id="hevea_default55"></a></p><p><span class="c006">When you type a statement in interactive mode, the interpreter
executes it and displays the result, if there is one.</span></p><p><span class="c006">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.</span></p><p><span class="c006">For example, the script</span></p><pre class="verbatim"><span class="c004">print 1
x = 2
print x
</span></pre><p><span class="c006">produces the output</span></p><pre class="verbatim"><span class="c004">1
2
</span></pre><p><span class="c006">The assignment statement produces no output.</span></p><span class="c005">
</span><h2 class="section" id="sec22"><span class="c006">2.5  Operators and operands</span></h2>
<p><span class="c005">
</span><a id="hevea_default56"></a><span class="c005">
</span><a id="hevea_default57"></a><span class="c005">
</span><a id="hevea_default58"></a><span class="c005">
</span><a id="hevea_default59"></a></p><p><span class="c006"><span class="c009">Operators</span> are special symbols that represent computations like
addition and multiplication. The values the operator is applied to
are called <span class="c009">operands</span>.</span></p><p><span class="c006">The operators <span class="c001">+</span>, <span class="c001">-</span>, <span class="c001">*</span>, <span class="c001">/</span>, and <span class="c001">**</span>
perform addition, subtraction, multiplication, division, and
exponentiation, as in the following examples:</span></p><pre class="verbatim"><span class="c004">20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
</span></pre><p><span class="c006">The division operator might not do what you expect:</span></p><pre class="verbatim"><span class="c004">>>> minute = 59
>>> minute/60
0
</span></pre><p><span class="c006">The value of <span class="c001">minute</span> 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 <span class="c009">floor division</span></span><sup><a id="text4" href="#note4"><span class="c006">2</span></a></sup><span class="c006">.</span></p><p><a id="hevea_default60"></a><span class="c005">
</span><a id="hevea_default61"></a><span class="c005">
</span><a id="hevea_default62"></a><span class="c005">
</span><a id="hevea_default63"></a><span class="c005">
</span><a id="hevea_default64"></a></p><p><span class="c006">When both of the operands are integers, the result is also an
integer; floor division chops off the fractional
part, so in this example it truncates the answer to zero.</span></p><p><span class="c006">If either of the operands is a floating-point number, Python performs
floating-point division, and the result is a <span class="c001">float</span>:</span></p><pre class="verbatim"><span class="c004">>>> minute/60.0
0.98333333333333328
</span></pre><span class="c005">
</span><h2 class="section" id="sec23"><span class="c006">2.6  Expressions</span></h2>
<p><span class="c006">An <span class="c009">expression</span> 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 <span class="c001">x</span> has been assigned a value):</span></p><p><a id="hevea_default65"></a><span class="c005">
</span><a id="hevea_default66"></a></p><pre class="verbatim"><span class="c004">17
x
x + 17
</span></pre><p><span class="c006">If you type an expression in interactive mode, the interpreter
<span class="c009">evaluates</span> it and displays the result:</span></p><pre class="verbatim"><span class="c004">>>> 1 + 1
2
</span></pre><p><span class="c006">But in a script, an expression all by itself doesn’t
do anything! This is a common
source of confusion for beginners.</span></p><div class="theorem"><span class="c006"><span class="c009">Exercise 1</span>  <em>
Type the following statements in the Python interpreter to see
what they do:</em></span><pre class="verbatim"><span class="c004"><em>5
x = 5
x + 1
</em></span></pre></div><span class="c005">
</span><h2 class="section" id="sec24"><span class="c006">2.7  Order of operations</span></h2>
<p><span class="c005">
</span><a id="hevea_default67"></a><span class="c005">
</span><a id="hevea_default68"></a><span class="c005">
</span><a id="hevea_default69"></a></p><p><span class="c006">When more than one operator appears in an expression, the order of
evaluation depends on the <span class="c009">rules of precedence</span>. For
mathematical operators, Python follows mathematical convention.
The acronym <span class="c009">PEMDAS</span> is a useful way to
remember the rules:</span></p><p><a id="hevea_default70"></a></p><ul class="itemize"><li class="li-itemize"><span class="c006"><span class="c009">P</span>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, <span class="c001">2 * (3-1)</span> is 4,
and <span class="c001">(1+1)**(5-2)</span> is 8. You can also use parentheses to make an
expression easier to read, as in <span class="c001">(minute * 100) / 60</span>, even
if it doesn’t change the result.</span></li><li class="li-itemize"><span class="c006"><span class="c009">E</span>xponentiation has the next highest precedence, so
<span class="c001">2**1+1</span> is 3, not 4, and <span class="c001">3*1**3</span> is 3, not 27.</span></li><li class="li-itemize"><span class="c006"><span class="c009">M</span>ultiplication and <span class="c009">D</span>ivision have the same precedence,
which is higher than <span class="c009">A</span>ddition and <span class="c009">S</span>ubtraction, which also
have the same precedence. So <span class="c001">2*3-1</span> is 5, not 4, and
<span class="c001">6+4/2</span> is 8, not 5.</span></li><li class="li-itemize"><span class="c006">Operators with the same precedence are evaluated from left to
right. So the expression <span class="c001">5-3-1</span> is 1, not 3, because the
<span class="c001">5-3</span> happens first and then <span class="c001">1</span> is subtracted from <span class="c001">2</span>.</span></li></ul><p><span class="c006">When in doubt, always put parentheses in your expressions to make sure
the computations are performed in the order you intend.</span></p><span class="c005">
</span><h2 class="section" id="sec25"><span class="c006">2.8  Modulus operator</span></h2>
<p><a id="hevea_default71"></a><span class="c005">
</span><a id="hevea_default72"></a></p><p><span class="c006">The <span class="c009">modulus operator</span> works on integers and yields the remainder
when the first operand is divided by the second. In Python, the
modulus operator is a percent sign (<code>%</code>). The syntax is the same
as for other operators:</span></p><pre class="verbatim"><span class="c004">>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
</span></pre><p><span class="c006">So 7 divided by 3 is 2 with 1 left over.</span></p><p><span class="c006">The modulus operator turns out to be surprisingly useful. For
example, you can check whether one number is divisible by another—if
<span class="c001">x % y</span> is zero, then <span class="c001">x</span> is divisible by <span class="c001">y</span>.</span></p><p><a id="hevea_default73"></a></p><p><span class="c006">You can also extract the right-most digit
or digits from a number. For example, <span class="c001">x % 10</span> yields the
right-most digit of <span class="c001">x</span> (in base 10). Similarly, <span class="c001">x % 100</span>
yields the last two digits.</span></p><span class="c005">
</span><h2 class="section" id="sec26"><span class="c006">2.9  String operations</span></h2>
<p><span class="c005">
</span><a id="hevea_default74"></a><span class="c005">
</span><a id="hevea_default75"></a></p><p><span class="c006">The <span class="c001">+</span> operator works with strings, but it
is not addition in the mathematical sense. Instead it performs
<span class="c009">concatenation</span>, which means joining the strings by
linking them end to end. For example:</span></p><p><a id="hevea_default76"></a></p><pre class="verbatim"><span class="c004">>>> first = 10
>>> second = 15
>>> print first+second
25
>>> first = '100'
>>> second = '150'
>>> print first + second
100150
</span></pre><p><span class="c006">The output of this program is <span class="c001">100150</span>.</span></p><span class="c005">
</span><h2 class="section" id="sec27"><span class="c006">2.10  Asking the user for input</span></h2>
<p><span class="c005">
</span><a id="hevea_default77"></a></p><p><span class="c006">Sometimes we would like to take the value for a variable from the user
via their keyboard.
Python provides a built-in function called <code>raw_input</code> that gets
input from the keyboard</span><sup><a id="text5" href="#note5"><span class="c006">3</span></a></sup><span class="c006">. When this function is called, the program stops and
waits for the user to type something. When the user presses <span class="c003">Return</span> or <span class="c003">Enter</span>, the program resumes and <code>raw_input</code>
returns what the user typed as a string.</span></p><p><a id="hevea_default78"></a><span class="c005">
</span><a id="hevea_default79"></a><span class="c005">
</span><a id="hevea_default80"></a></p><pre class="verbatim"><span class="c004">>>> input = raw_input()
Some silly stuff
>>> print input
Some silly stuff
</span></pre><p><span class="c006">Before getting input from the user, it is a good idea to print a
prompt telling the user what to input. You can pass a string
to <code>raw_input</code> to be displayed to the user before pausing
for input:</span></p><p><a id="hevea_default81"></a></p><pre class="verbatim"><span class="c004">>>> name = raw_input('What is your name?\n')
What is your name?
Chuck
>>> print name
Chuck
</span></pre><p><span class="c006">The sequence <code>\n</code> at the end of the prompt represents a <span class="c009">newline</span>,
which is a special character that causes a line break.
That’s why the user’s input appears below the prompt.</span></p><p><a id="hevea_default82"></a></p><p><span class="c006">If you expect the user to type an integer, you can try to convert
the return value to <span class="c001">int</span> using the <span class="c001">int()</span> function:</span></p><pre class="verbatim"><span class="c004">>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
>>> int(speed) + 5
22
</span></pre><p><span class="c006">But if the user types something other than a string of digits,
you get an error:</span></p><pre class="verbatim"><span class="c004">>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()
</span></pre><p><span class="c006">We will see how to handle this kind of error later.</span></p><p><a id="hevea_default83"></a><span class="c005">
</span><a id="hevea_default84"></a></p><span class="c005">
</span><h2 class="section" id="sec28"><span class="c006">2.11  Comments</span></h2>
<p><span class="c005">
</span><a id="hevea_default85"></a></p><p><span class="c006">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.</span></p><p><span class="c006">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
<span class="c009">comments</span>, and in Python they start with the <code>#</code> symbol:</span></p><pre class="verbatim"><span class="c004"># compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
</span></pre><p><span class="c006">In this case, the comment appears on a line by itself. You can also put
comments at the end of a line:</span></p><pre class="verbatim"><span class="c004">percentage = (minute * 100) / 60 # percentage of an hour
</span></pre><p><span class="c006">Everything from the <span class="c001">#</span> to the end of the line is ignored—it
has no effect on the program.</span></p><p><span class="c006">Comments are most useful when they document non-obvious features of
the code. It is reasonable to assume that the reader can figure out
<em>what</em> the code does; it is much more useful to explain <em>why</em>.</span></p><p><span class="c006">This comment is redundant with the code and useless:</span></p><pre class="verbatim"><span class="c004">v = 5 # assign 5 to v
</span></pre><p><span class="c006">This comment contains useful information that is not in the code:</span></p><pre class="verbatim"><span class="c004">v = 5 # velocity in meters/second.
</span></pre><p><span class="c006">Good variable names can reduce the need for comments, but
long names can make complex expressions hard to read, so there is
a trade-off.</span></p><span class="c005">
</span><h2 class="section" id="sec29"><span class="c006">2.12  Choosing mnemonic variable names</span></h2>
<p><a id="hevea_default86"></a></p><p><span class="c006">As long as you follow the simple rules of variable naming, and avoid
reserved words, you have a lot of choice when you name your variables.
In the beginning, this choice can be confusing both when you read a
program and when you write your own programs. For example, the
following three programs are identical in terms of what they accomplish,
but very different when you read them and try to understand them.</span></p><pre class="verbatim"><span class="c004">a = 35.0
b = 12.50
c = a * b
print c
hours = 35.0
rate = 12.50
pay = hours * rate
print pay
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print x1q3p9afd
</span></pre><p><span class="c006">The Python interpreter sees all three of these programs as <em>exactly the
same</em> but humans see and understand these programs quite differently.
Humans will most quickly understand the <span class="c009">intent</span>
of the second program because the
programmer has chosen variable names that reflect their intent
regarding what data will be stored in each variable.</span></p><p><span class="c006">We call these wisely chosen variable names “mnemonic variable names”. The
word <em>mnemonic</em></span><sup><a id="text6" href="#note6"><span class="c006">4</span></a></sup><span class="c006">
means “memory aid”.
We choose mnemonic variable names to help us remember why we created the variable
in the first place.</span></p><p><span class="c006">While this all sounds great, and it is a very good idea to use mnemonic variable
names, mnemonic variable names can get in the way of a beginning programmer’s
ability to parse and understand code. This is because beginning programmers
have not yet memorized the reserved words (there are only 31 of them) and sometimes
variables with names that are too descriptive start to look like
part of the language and not just well-chosen variable names.</span></p><p><span class="c006">Take a quick look at the following Python sample code which loops through some data.
We will cover loops soon, but for now try to just puzzle through what this means:</span></p><pre class="verbatim"><span class="c004">for word in words:
print word
</span></pre><p><span class="c006">What is happening here? Which of the tokens (for, word, in, etc.) are reserved words
and which are just variable names? Does Python understand at a fundamental level
the notion of words? Beginning programmers have
trouble separating what parts of the
code <em>must</em> be the same as this example and what parts of the code are simply
choices made by the programmer.</span></p><p><span class="c006">The following code is equivalent to the above code:</span></p><pre class="verbatim"><span class="c004">for slice in pizza:
print slice
</span></pre><p><span class="c006">It is easier for the beginning programmer to look at this code and know which
parts are reserved words defined by Python and which parts are simply variable
names chosen by the programmer. It is pretty clear that Python has no fundamental
understanding of pizza and slices and the fact that a pizza consists of a set
of one or more slices.</span></p><p><span class="c006">But if our program is truly about reading data and looking for words in the data,
<span class="c001">pizza</span> and <span class="c001">slice</span> are very un-mnemonic variable names. Choosing them
as variable names distracts from the meaning of the program.</span></p><p><span class="c006">After a pretty short period of time, you will know the most common reserved words
and you will start to see the reserved words jumping out at you:</span></p><p><span class="c002"><span class="c009">for</span> word <span class="c009">in</span> words<span class="c009">:<br />
<code> </code>print</span> word </span></p><p><span class="c006">The parts of the code that are defined by
Python (<span class="c001">for</span>, <span class="c001">in</span>, <span class="c001">print</span>, and <span class="c001">:</span>) are in bold
and the programmer-chosen variables (<span class="c001">word</span> and <span class="c001">words</span>) are not in bold.
Many text editors are aware of Python
syntax and will color reserved words differently to give you clues to keep
your variables and reserved words separate.
After a while you will begin to read Python and quickly determine what
is a variable and what is a reserved word.</span></p><span class="c005">
</span><h2 class="section" id="sec30"><span class="c006">2.13  Debugging</span></h2>
<p><span class="c005">
</span><a id="hevea_default87"></a></p><p><span class="c006">At this point, the syntax error you are most likely to make is
an illegal variable name, like <span class="c001">class</span> and <span class="c001">yield</span>, which
are keywords, or <code>odd~job</code> and <code>US$</code>, which contain
illegal characters.</span></p><p><a id="hevea_default88"></a><span class="c005">
</span><a id="hevea_default89"></a></p><p><span class="c006">If you put a space in a variable name, Python thinks it is two
operands without an operator:</span></p><pre class="verbatim"><span class="c004">>>> bad name = 5
SyntaxError: invalid syntax
</span></pre><p><span class="c006">For syntax errors, the error messages don’t help much.
The most common messages are <span class="c001">SyntaxError: invalid syntax</span> and
<span class="c001">SyntaxError: invalid token</span>, neither of which is very informative.</span></p><p><a id="hevea_default90"></a><span class="c005">
</span><a id="hevea_default91"></a><span class="c005">
</span><a id="hevea_default92"></a><span class="c005">
</span><a id="hevea_default93"></a><span class="c005">
</span><a id="hevea_default94"></a></p><p><span class="c006">The runtime error you are most likely to make is a “use before
def;” that is, trying to use a variable before you have assigned
a value. This can happen if you spell a variable name wrong:</span></p><pre class="verbatim"><span class="c004">>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
</span></pre><p><span class="c006">Variables names are case sensitive, so <span class="c001">LaTeX</span> is not the
same as <span class="c001">latex</span>.</span></p><p><a id="hevea_default95"></a><span class="c005">
</span><a id="hevea_default96"></a><span class="c005">
</span><a id="hevea_default97"></a></p><p><span class="c006">At this point, the most likely cause of a semantic error is
the order of operations. For example, to evaluate 1/2 π,
you might be tempted to write</span></p><pre class="verbatim"><span class="c004">>>> 1.0 / 2.0 * pi
</span></pre><p><span class="c006">But the division happens first, so you would get π / 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’t
get an error message; you just get the wrong answer.</span></p><p><a id="hevea_default98"></a></p><span class="c005">
</span><h2 class="section" id="sec31"><span class="c006">2.14  Glossary</span></h2>
<dl class="description"><dt class="dt-description"><span class="c010">assignment:</span></dt><dd class="dd-description"><span class="c006"> A statement that assigns a value to a variable.
</span><a id="hevea_default99"></a></dd><dt class="dt-description"><span class="c010">concatenate:</span></dt><dd class="dd-description"><span class="c006"> To join two operands end to end.
</span><a id="hevea_default100"></a></dd><dt class="dt-description"><span class="c010">comment:</span></dt><dd class="dd-description"><span class="c006"> 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.
</span><a id="hevea_default101"></a></dd><dt class="dt-description"><span class="c010">evaluate:</span></dt><dd class="dd-description"><span class="c006"> To simplify an expression by performing the operations
in order to yield a single value.</span></dd><dt class="dt-description"><span class="c010">expression:</span></dt><dd class="dd-description"><span class="c006"> A combination of variables, operators, and values that
represents a single result value.
</span><a id="hevea_default102"></a></dd><dt class="dt-description"><span class="c010">floating point:</span></dt><dd class="dd-description"><span class="c006"> A type that represents numbers with fractional
parts.
</span><a id="hevea_default103"></a></dd><dt class="dt-description"><span class="c010">floor division:</span></dt><dd class="dd-description"><span class="c006"> The operation that divides two numbers and chops off
the fractional part.
</span><a id="hevea_default104"></a></dd><dt class="dt-description"><span class="c010">integer:</span></dt><dd class="dd-description"><span class="c006"> A type that represents whole numbers.
</span><a id="hevea_default105"></a></dd><dt class="dt-description"><span class="c010">keyword:</span></dt><dd class="dd-description"><span class="c006"> A reserved word that is used by the compiler to parse a
program; you cannot use keywords like <span class="c001">if</span>, <span class="c001">def</span>, and <span class="c001">while</span> as
variable names.
</span><a id="hevea_default106"></a></dd><dt class="dt-description"><span class="c010">mnemonic:</span></dt><dd class="dd-description"><span class="c006"> A memory aid. We often give variables mnemonic names
to help us remember what is stored in the variable.
</span><a id="hevea_default107"></a></dd><dt class="dt-description"><span class="c010">modulus operator:</span></dt><dd class="dd-description"><span class="c006"> An operator, denoted with a percent sign
(<span class="c001">%</span>), that works on integers and yields the remainder when one
number is divided by another.
</span><a id="hevea_default108"></a><span class="c005">
</span><a id="hevea_default109"></a></dd><dt class="dt-description"><span class="c010">operand:</span></dt><dd class="dd-description"><span class="c006"> One of the values on which an operator operates.
</span><a id="hevea_default110"></a></dd><dt class="dt-description"><span class="c010">operator:</span></dt><dd class="dd-description"><span class="c006"> A special symbol that represents a simple computation like
addition, multiplication, or string concatenation.
</span><a id="hevea_default111"></a></dd><dt class="dt-description"><span class="c010">rules of precedence:</span></dt><dd class="dd-description"><span class="c006"> The set of rules governing the order in which
expressions involving multiple operators and operands are evaluated.
</span><a id="hevea_default112"></a><span class="c005">
</span><a id="hevea_default113"></a></dd><dt class="dt-description"><span class="c010">statement:</span></dt><dd class="dd-description"><span class="c006"> A section of code that represents a command or action. So
far, the statements we have seen are assignments and print statements.
</span><a id="hevea_default114"></a></dd><dt class="dt-description"><span class="c010">string:</span></dt><dd class="dd-description"><span class="c006"> A type that represents sequences of characters.
</span><a id="hevea_default115"></a></dd><dt class="dt-description"><span class="c010">type:</span></dt><dd class="dd-description"><span class="c006"> A category of values. The types we have seen so far
are integers (type <span class="c001">int</span>), floating-point numbers (type <span class="c001">float</span>), and strings (type <span class="c001">str</span>).
</span><a id="hevea_default116"></a></dd><dt class="dt-description"><span class="c010">value:</span></dt><dd class="dd-description"><span class="c006"> One of the basic units of data, like a number or string,
that a program manipulates.
</span><a id="hevea_default117"></a></dd><dt class="dt-description"><span class="c010">variable:</span></dt><dd class="dd-description"><span class="c006"> A name that refers to a value.
</span><a id="hevea_default118"></a></dd></dl><span class="c005">
</span><h2 class="section" id="sec32"><span class="c006">2.15  Exercises</span></h2>
<div class="theorem"><span class="c006"><span class="c009">Exercise 2</span>  <em>
Write a program that uses <code>raw_input</code> to prompt a user for their name
and then welcomes them.</em></span><pre class="verbatim"><span class="c006"><em>Enter your name: Chuck
Hello Chuck
</em></span></pre></div><div class="theorem"><span class="c006"><span class="c009">Exercise 3</span>  <em>
Write a program to prompt the user for hours and rate per hour to compute
gross pay.
</em></span><pre class="verbatim"><span class="c006"><em>Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
</em></span></pre></div><p><span class="c006">
We won’t worry about making sure our pay has exactly two digits after
the decimal place for now. If you want, you can play with the
built-in Python <span class="c001">round</span> function to properly round the resulting pay
to two decimal places.</span></p><div class="theorem"><span class="c006"><span class="c009">Exercise 4</span>  <em>
Assume that we execute the following assignment statements:</em></span><pre class="verbatim"><span class="c006"><em>width = 17
height = 12.0
</em></span></pre><p><span class="c006"><em>For each of the following expressions, write the value of the
expression and the type (of the value of the expression).</em></span></p><ol class="enumerate" type="1"><li class="li-enumerate"><span class="c002"><em>width/2</em></span></li><li class="li-enumerate"><span class="c002"><em>width/2.0</em></span></li><li class="li-enumerate"><span class="c002"><em>height/3</em></span></li><li class="li-enumerate"><span class="c002"><em>1 + 2 * 5</em></span></li></ol><p><span class="c006"><em>Use the Python interpreter to check your answers.
</em></span></p></div><div class="theorem"><span class="c006"><span class="c009">Exercise 5</span>  <em>
Write a program which prompts the user for a Celsius temperature,
convert the temperature to Fahrenheit, and print out the converted
temperature.
</em></span></div><span class="c005">
</span><hr class="footnoterule" /><dl class="thefootnotes"><dt class="dt-thefootnotes"><span class="c005">
</span><a id="note3" href="#text3"><span class="c006">1</span></a></dt><dd class="dd-thefootnotes"><span class="c006"><div class="footnotetext">In Python 3.0, <span class="c001">exec</span> is no
longer a keyword, but <span class="c001">nonlocal</span> is.</div>
</span></dd><dt class="dt-thefootnotes"><a id="note4" href="#text4"><span class="c006">2</span></a></dt><dd class="dd-thefootnotes"><span class="c006"><div class="footnotetext">In Python 3.0,
the result of this division is a <span class="c001">float</span>.
In Python 3.0, the new operator
<span class="c001">//</span> performs integer division.</div>
</span></dd><dt class="dt-thefootnotes"><a id="note5" href="#text5"><span class="c006">3</span></a></dt><dd class="dd-thefootnotes"><span class="c006"><div class="footnotetext">In Python 3.0, this function is named
<span class="c001">input</span>.</div>
</span></dd><dt class="dt-thefootnotes"><a id="note6" href="#text6"><span class="c006">4</span></a></dt><dd class="dd-thefootnotes"><span class="c006"><div class="footnotetext">See
<span class="c001">http://en.wikipedia.org/wiki/Mnemonic</span>
for an extended description of the word “mnemonic”.</div>
</span></dd></dl>
<hr />
<a href="book002.html"><img src="previous_motif.gif" alt="Previous" /></a>
<a href="index.html"><img src="contents_motif.gif" alt="Up" /></a>
<a href="book004.html"><img src="next_motif.gif" alt="Next" /></a>
</body>
</html>