forked from ninas/umonya_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram_state.html
417 lines (314 loc) · 16.2 KB
/
program_state.html
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Introductory Programming in Python: Program State and Basic Variables</title>
<link rel='stylesheet' type='text/css' href='style.css' />
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script src="animation.js" type="text/javascript">
</script>
</head>
<body onload="animate_loop()">
<div class="page">
<h1>Introductory Programming in Python: Lesson 5<br />
Program State and Basic Variables</h1>
<div class="centered">
[<a href="basic_input.html">Prev: Basic Input</a>] [<a href="index.html">Course Outline</a>] [<a href="conditionals.html">Next: Flow control: Conditionals</a>]
</div>
<h2>The Concept of State</h2>
<p>As we know, programs execute statements in sequential order. They
flow through your code, left to right, top to bottom. As statements are
executed, things happen; output is issued, calculations are done, and
the <strong>state</strong> of your program changes. But what is state?
Loosely put, state refers to all the data your program is dealing with
and their <strong>current</strong> values at the point in time when a
particular statement is about to be executed. Since the entire point of
a program is to transform input data into some meaningful output data,
it stands to reason that the program will modify the values of the data
it is dealing with. This occurs in a stepwise fashion, statement by
executed statement. But we need a way to record the state of our
program in conveniently manageable units, which we shall call
<strong>variables</strong>, as their value may vary over the course of
program execution.</p>
<p>Variables each have a name, a type, and a value. A name is simply
the name we choose to call a particular piece of data. For example, we
previously called the bit of data representing the total number of
apples held by everyone 'apples'. The value of apples started at 0, and
as more people were inputed into the problem, the number of apples
increased and so, accordingly, did the value of our variable
'apples'.</p>
<p><strong>Type</strong> refers to the type of value a variable can
have. Text is not the same as a number, thus they are considered
different types. One could not for example add "apples" to the number
7. Python has five basic types:</p>
<dl>
<dt>int</dt>
<dd>Integers, e.g. 1, 179835646, -3, 0</dd>
<dt>string</dt>
<dd>Text strings, e.g. 'Alice', "The cat sat on the mat"</dd>
<dt>float</dt>
<dd>Real numbers, e.g. 0.0, 48747.23501, -0.5</dd>
<dt>bool</dt>
<dd>Boolean conditions, e.g. True, False</dd>
<dt>None</dt>
<dd>None is both a value and a type specifying a value that is not
of any type nor has any actual value.</dd>
</dl>
<h2>Assignment Statements</h2>
<p>To create a new variable for use we simply <strong>assign</strong>
it a value, by giving it a name and setting the name equal to the
value. We do this by using the <strong>assignment statement</strong>
which takes the form</p>
<div class="centered">
<em>variable_name = expression</em>
</div>
<pre class='listing'>
Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [MSC v.1310 32 bit (Intel)] on win32
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "James"
>>>
</pre>
<p>Here we have created a new variable, whose name is 'name', and which
has the value <em>James</em>. We did not explicitly state the type of
'name' to be a string, as python takes care of this for us. When
assigning a value to a variable, python automatically sets the type of
variable being assigned to the type of the value being assigned. If we
go on to assign name again, this time with a different value</p>
<pre class='listing'>
>>> name = "Jimbo"
>>>
</pre>
<p>The value of 'name' has changed. If we want to see what the value of
a variable is we can simply print it:</p>
<pre class='listing'>
>>> print name
Jimbo
>>>
</pre>
<p>James has disappeared. As far as the program is concerned James was
never there. There is no James! Assigning a new value to a variable
will obliterate the previous value of that variable. If you wish to
keep the old value of a variable you need to save a copy, in a
different variable.</p>
<pre class='listing'>
>>> i = 1
>>> j = i
>>> i = 2
>>> print "i =", i, "and j =", j
i = 2 and j = 1
>>>
</pre>
<p>So let's look at what we've done, step by step.</p>
<ol>
<li><code>i = 1</code><br />
We create a new variable, called 'i', assign it a value of
<em>1</em>, and python sets it's type to 'int'</li>
<li><code>j = i</code><br />
We create another new variable, this time called 'j', assign it a
value of ... well what exactly? <code>i</code> is not a string
because it's not in quotes, and it's not a number, so it's being
treated as a variable. But what is 'i'? Variables are implicitly
considered to be their current values. So <code>i</code> is
implicitly considered to be 1 (it's current value)</li>
<li><code>i = 2</code><br />
We assign a new value to 'i'. The old value of 'i' is
discarded.</li>
<li><code>print "i =", i, "and j =", j</code><br />
We output the current values of 'i' and 'j' respectively.</li>
</ol>
<p>Step 2 highlights a number of important points about assignment. The
assignment statement does something very specific. It changes the
current value of the variable being assigned to the value of the
expression to the right of the equals. This means that the value of the
expression must be determined before actually changing the value of the
variable. As you can see from the output produced by our little
program, assignments do not 'hold true' over time in the same way as a
similar statement in maths does. <code>j = i</code> does not mean that
'j' and 'i' are always equivalent. The only thing that can be certainly
said about the relationship between 'j' and 'i' is that they will be
equal directly after the assignment statement has been executed. Both
before and after that point in time, all bets are off.</p>
<div class="centered">
An assignment is <strong>not</strong> a description of a
relationship between two expressions.<br /> It effects a
<strong>once off</strong> change in the value of one variable.
</div>
<p>Consider the assignment statement <code>x = x + 1</code>. For those
of you with inner mathematicians that are screaming loudly to get out,
take a large stiff drink now! What we have is an assignment to a
variable ('x') the value of an expression ('x + 1'). Let us suppose
that currently the value of 'x' is 1. This assignment occurs as
follows.</p>
<ol>
<li><code>x = x + 1</code><br />
The value of the expression 'x + 1' is determined. Since 'x' is 1,
and complex expressions are built out of simple atomic expressions
using operators like '+', we can transform the expression into '1 +
1' since variables are considered in expressions to be their
current value.</li>
<li><code>x = 1 + 1</code><br />
This is obviously 2, hence the value of the expression overall is
2.</li>
<li><code>x = 2</code><br />
2 is assigned as the <strong>new</strong> value of 'x'.</li>
</ol>
<h2>Integers, Floats and Arithmetic Expressions</h2>
<p>Obviously we want to be able do more than simply assign values to
variables. We need to be able to manipulate and combine them in various
ways. For integers and floats this leads directly to arithmetic
notation, and its representations in python. Also how can we determine
how variables of different types act when manipulated arithmetically.
In general basic arithmetic expressions can be formed in much the same
way as one would express them mathematically. If 'x' and 'y' are either
integers or floats then</p>
<ul>
<li><code>x + y</code> yields Addition</li>
<li><code>x - y</code> yields Subtraction</li>
<li><code>x * y</code> yields Multiplication</li>
<li><code>x / y</code> yields Division</li>
<li><code>x % y</code> yields Modulo (or Remainder)</li>
<li><code>x ** y</code> yields Exponentiation (or raising to the power of)</li>
</ul>
<p>The above list describes various <strong>operators</strong> that can
be used to form arithmetic expressions. But, suppose we have the
expression <code>2+3*4</code>. Which of the addition or the
multiplication operators is applied first? One might think the
operators are applied simply left to right, but as in maths, instead we
have a well defined order of <strong>precedence</strong> specifying
which operators are applied and in what order. The complete list of
python operators and their precedence can be found <a class="doclink"
href="http://olympiad.cs.uct.ac.za/docs/python-docs-2.6/reference/expressions.html#summary">here</a>. In general
python arithmetic operates exactly as it would in normal
mathematics.</p>
<p>In the same way variables have a type, so too do expressions have a
type associated with their value. The type of the value of an
expression is generally determined by the types comprising the
expression. For example, adding one integer to another in an expression
always yields an integer, so the expression has type integer. But what
happens when you mix two, or more, types in an expression? In general
all participating sub-expressions have their type promoted to the most
general type. By general, we mean 'most capable of representing all
types involved'. For example, the value 0.5 cannot be represented by an
integer, but the value 3 can be represented by a float as in 3.0. Hence
adding a float to an integer means the integer gets promoted to a float
and the type of the value of the expression as a whole will be a float.
Division however acts slightly differently:</p>
<pre class='listing'>
>>> print 4/2
2
>>> print 5/2
2
>>>
</pre>
<p>Four divided by two is two, no problems there. But five divided two
is 2.5, not 2! Because both 5 and 2 are integers, python divides them
as integers, in much the same way as we did in junior school. The
number of times 2 goes into 5 completely is worked out, and the rest is
considered the remainder. Because an integer can't represent the
additional 0.5, it is simply dropped. If you want the exact value,
divide by a float instead, and force promotion of the expression to a
float:</p>
<pre class='listing'>
>>> print 5/2.0
2.5
>>>
</pre>
<p>However, often we actually want the integer part of a division only,
and equally so the remainder. Python provides us with an operator to
get the remainder, namely modulo:</p>
<pre class='listing'>
>>> print 5 % 2
1
>>> print "5 divided by 2 is ", 5/2, "remainder", 5 % 2
5 divided by 2 is 2 remainder 1
>>>
</pre>
<h2>Strings and common operators</h2>
<p>Strings can be manipulated too, but the operations we perform on
them are fundamentally different. Assuming 's1' and 's2' are strings,
and 'i' and 'j' are integers</p>
<ul>
<li><code>s1 + s2</code> yields Concatenation<br />
The joining of two strings in the order they are listed as operands
to from a single string; e.g. <code>"a"+"b"</code> yields "ab"</li>
<li><code>s1 * i</code> yields Repetition<br />
The creation of a new string repeated 'i' times; e.g. <code>"a" *
3</code> yields "aaa"</li>
<li><code>s1[i]</code> yields Subscription (or indexing)<br />
The extraction of a single character at a specific position in the
string, where the first character in the string is a position 0,
the second and position 1, and so on; e.g. <code>"abc"[1]</code>
yields "b". 'i' may be any expression evaluating to an integer.
Negative numbers may be used, where <code>-i</code> means the i'th
last position.</li>
<li><code>s1[i:j:k]</code> yields Slicing<br />
The extraction of a series of characters from a string starting at
the character in the i'th position and continuing until the
character just prior to the j'th position, extracting only every
k'th character, where positions are numbered from 0, and negative
number mean distance from end of string. Any of i, j, or k may be
omited, in which case they are treated as 0, the string length, and
1 respectively. A k value of 1 means all characters in the
specified range are extracted. If 'j' is omitted, the extraction is
from the 'i'th position to the end of the string. Examples:<br />
<code>"The <b>quick brown fox</b>"[4:]</code> yields "quick brown fox"<br />
<code>"The quick brown<b> fox</b>"[-4:]</code> yields " fox"<br />
<code>"<b>The </b>quick brown fox"[:4]</code> yields "The "<br />
<code>"The <b>quick</b> brown fox"[4:9]</code> yields "quick".<br />
<code>"<b>T</b>h<b>e</b> <b>q</b>u<b>i</b>c<b>k</b> <b>b</b>r<b>o</b>w<b>n</b> <b>f</b>o<b>x</b>"[::2]</code> yields "Teqikbonfx"<br />
<code>"The <b>q</b>ui<b>c</b>k <b>b</b>ro<b>w</b>n fox"[4:15:3]</code> yields "qcbw".<br /></li>
<li><code>s1[:]</code> yields Slicing of the entire string,
essentially making a complete copy of the string.</li>
</ul>
<h2>Formalisation of the Concepts of Statements and Expressions</h2>
<p>To recap, in a more formal way.</p>
<ol>
<li>Programs consist of sequences of statements</li>
<li>Statements perform actions but do not have value</li>
<li>Statements may act on expressions</li>
<li>Expressions have a value, and when used in statements, their value is determined and substituted in place of the expression</li>
<li>Expressions may be simple expressions such as numbers or variables whose values can be determined directly</li>
<li>Expressions may be composed of simpler expressions combined using appropriate operators</li>
</ol>
<h2>Exercises</h2>
<ol>
<li>What does the assignment statement do?</li>
<li>What are the five basic variable types in python?</li>
<li>If the integer variable <em>i</em> has the value 7, then what is
the value of the expression <code class='value'>7/4</code>. Why?</li>
<li>How does one calculate the remainder (modulo) of an integer when
divided by another number?</li>
<li>Write a program that asks the user for a number from 1 to 31.
Assume the first day of the month is a Sunday. Output the name of
the weekday of the day of month the user entered.</li>
<li>Write a program that outputs the letter "x" 1000 times on a
single line, without intervening spaces.</li>
<li>If <em>s</em> is a sting variable with the value "Harry's Hippie
Hoedown", then what is the value of<br /><code class='value'>s + ": tickets only
$5"</code></li>
<li>If <em>s</em> is a sting variable with the value "Harry's Hippie
Hoedown", then what is the value of<br /><code class='value'>s + ": tickets only
$" + "5"*3</code></li>
<li>What is the value of <code class='value'>"ABBA was a Swedish band popular during the
80's"[0:4]</code>?</li>
<li>What is the value of <code class='value'>"ABBA was a Swedish band popular during the
80's"[-15:-7]</code>?</li>
<li>If the string variable <em>s</em> has the value "ABBA was a
Swedish band popular during the 80's", then what is the value of
<br /><code
class='value'>"BAAB"+s[4:11]+"Danish"+s[18:24]+"un"+s[24:-4]+"90's"</code></li>
<li>What is your favourite sport? Write a program that inputs the score
units for this sport (e.g. for rugby: number of tries, conversions,
penalties, time played) and works out some statistics (e.g. the total
score, average points per minute, time remaining, expected final score).
</ol>
<div class="centered">
[<a href="basic_input.html">Prev: Basic Input</a>] [<a href="index.html">Course Outline</a>] [<a href="conditionals.html">Next: Flow control: Conditionals</a>]
</div>
</div>
<div class="pagefooter">
Copyright © James Dominy 2007-2008; Released under the <a href="http://www.gnu.org/copyleft/fdl.html">GNU Free Documentation License</a><br />
<a href="intropython.tar.gz">Download the tarball</a>
</div>
</body>
</html>