JythonBook / html / chapter3.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
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Chapter 3: Operators, Expressions, and Program Flow &mdash; Jython Book v0.1 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '0.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="Jython Book v0.1 documentation" href="index.html" />
    <link rel="next" title="Chapter 5: Exception Handling and Debugging" href="chapter5.html" />
    <link rel="prev" title="Chapter 2: Data Types and Referencing" href="chapter2.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="chapter5.html" title="Chapter 5: Exception Handling and Debugging"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="chapter2.html" title="Chapter 2: Data Types and Referencing"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="chapter-3-operators-expressions-and-program-flow">
<h1>Chapter 3: Operators, Expressions, and Program Flow<a class="headerlink" href="#chapter-3-operators-expressions-and-program-flow" title="Permalink to this headline"></a></h1>
<p>Up until this point, we’ve have not yet covered the different means of writing expressions in Python.  The focus of this chapter is to go in depth on each of the ways we can evaluate code, and write meaningful blocks of conditional logic.  We’ll cover the details of each operator that can be used in Python expressions.  This chapter will also cover some topics that have already been discussed in more meaningful detail.</p>
<p>We will begin by discussing details of expressions.  We have already seen some expressions in use while reading through the previous chapters.  Here we will focus more on the internals of operators used to create expressions, and also different types of expressions that we can use.  This chapter will go into further detail on how we can define blocks of code for looping and conditionals.</p>
<div class="section" id="types-of-expressions">
<h2>Types of Expressions<a class="headerlink" href="#types-of-expressions" title="Permalink to this headline"></a></h2>
<p>An expression in Python is a block of code that produces a result or value.  Most often, we think of expressions that are used to perform mathematical operations within our code.  However, there are a multitude of expressions used for other purposes as well.  In Chapter 2, we covered the details of String manipulation, sequence and dictionary operations, and touched upon working with sets.  All of the operations performed on these objects are forms of expressions in Python.</p>
<p>This chapter will go into detail on how you write and evaluate mathematical expressions, boolean expressions, and augmented assignments.</p>
</div>
<div class="section" id="mathematical-operations">
<h2>Mathematical Operations<a class="headerlink" href="#mathematical-operations" title="Permalink to this headline"></a></h2>
<p>The Python language of course contains all of your basic mathematical operations.  This section will briefly touch upon each operator that is available for use in Python and how they function.  You will also learn about a few built-in functions which can be used to assist in  your mathematical expressions.  Finally, you’ll see how to use conditionals in the Python language and learn order of evaluation.</p>
<p>Assuming that this is not the first programming language you are learning, there is no doubt that you are at least somewhat familiar with performing mathematical operations within your programs.  Python is no different than the rest when it comes to mathematics, as with most programming languages, performing mathematical computations and working with numeric expressions is straightforward.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operator</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>&#8216;+&#8217;</td>
<td>Addition</td>
</tr>
<tr><td>&#8216;-&#8216;</td>
<td>Subtraction</td>
</tr>
<tr><td>&#8216;*&#8217;</td>
<td>Multiplication</td>
</tr>
<tr><td>/</td>
<td>Division</td>
</tr>
<tr><td>//</td>
<td>Truncating Division</td>
</tr>
<tr><td>%</td>
<td>Modulo (Remainder of Division)</td>
</tr>
<tr><td><a href="#id1"><span class="problematic" id="id2">**</span></a></td>
<td>Power Operator</td>
</tr>
<tr><td>+var</td>
<td>Unary Plus</td>
</tr>
<tr><td>-var</td>
<td>Unary Minus</td>
</tr>
</tbody>
</table>
<p>Table 3-1:  Numeric Operators</p>
<p>Most of the operators in the table above are easily understood.  However, the truncating division, modulo, power, and unary operators could use some explanation.  Truncating division will automatically truncate a division result into an integer.  Modulo will return the remainder of a division operation.  The power operator does just what you’d expect as it returns the result of the number to the left of the operator multiplied by itself n times, where n represents the number to the right of the operator.  Unary plus and unary minus are used to evaluate positive or negative numbers.  The following set of examples will help to clarify these topics.</p>
<div class="highlight-python"><pre># Performing basic mathematical computations

&gt;&gt;&gt; 10 - 6
4
&gt;&gt;&gt; 9 * 7
63
&gt;&gt;&gt; 9 / 3
3
&gt;&gt;&gt; 10 / 3
3
&gt;&gt;&gt; 10 // 3
3
&gt;&gt;&gt; 3.14 / 2
1.57
&gt;&gt;&gt; 3.14 // 2
1.0
&gt;&gt;&gt; 36 / 5
7
&gt;&gt;&gt; 36 % 5
1
&gt;&gt;&gt; 5**2
25
&gt;&gt;&gt; 100**2
10000
&gt;&gt;&gt; -10 + 5
-5
&gt;&gt;&gt; +5 - 5
0</pre>
</div>
<p>There is a new means of division available in Jython 2.5 by importing from __future__.  In a standard division for 2.5 and previous releases, the quotient returned is an integer or the floor of the quotient when arguments are ints or longs.  However, a reasonable approximation of the division is returned if the arguments are floats or complex.  Often times this solution is incorrect as the quotient should be the reasonable approximation or “true division” in any case.  When we import <em>division</em> from the __future__ module then we alter the return value of division by causing true division when using the / operator, and floor division when using the // operator.  Since this is going to be the standard in future releases, it is best practice to import from __future__ when performing division in Jython 2.5.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">division</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">9</span><span class="o">/</span><span class="mf">5</span>
<span class="go">1.8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">9</span><span class="o">/</span><span class="mf">4</span>
<span class="go">2.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">9</span><span class="o">/</span><span class="mf">3</span>
<span class="go">3.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">9</span><span class="o">//</span><span class="mf">3</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">9</span><span class="o">//</span><span class="mf">5</span>
<span class="go">1</span>
</pre></div>
</div>
<p>As stated at the beginning of the section, there are a number of built-in mathematical functions that are at your disposal.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Function</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>abs(var)</td>
<td>Absolute value</td>
</tr>
<tr><td>pow(x, y)</td>
<td>Used in place of power operator</td>
</tr>
<tr><td>pow(x,y,modulo)</td>
<td>Ternary power-modulo</td>
</tr>
<tr><td>round(var[, n])</td>
<td>Returns a value rounded to the nearest 10-n</td>
</tr>
<tr><td>divmod(x, y)</td>
<td>Returns both the quotient and remainder of division operation</td>
</tr>
</tbody>
</table>
<p>Table 3-2:  Mathematical Built-in functions</p>
<div class="highlight-python"><pre>#  The following code provides some examples for using mathematical built-ins
&gt;&gt;&gt; abs(9)
9
&gt;&gt;&gt; abs(-9)
9
&gt;&gt;&gt; divmod(8,4)
(2, 0)
&gt;&gt;&gt; pow(8,2)
64
&gt;&gt;&gt; pow(8,2,3)
1
&gt;&gt;&gt; round(5.67,1)
5.7
&gt;&gt;&gt; round(5.67)
6.0</pre>
</div>
<p>The bitwise and logical operators as well as the conditional operators can be used to combine and compare logic.  As with the mathematical operators described above, these operators have no significant difference to that of Java.</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operator</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>&gt;</td>
<td>Greater than</td>
</tr>
<tr><td>&lt;</td>
<td>Less than</td>
</tr>
<tr><td>&gt;=</td>
<td>Greater than or equal</td>
</tr>
<tr><td>&lt;=</td>
<td>Less than or equal</td>
</tr>
<tr><td>!=</td>
<td>Not equal</td>
</tr>
<tr><td>==</td>
<td>Equal</td>
</tr>
<tr><td>&amp;</td>
<td>Bitwise and</td>
</tr>
<tr><td><div class="first last line-block">
<div class="line"><br /></div>
</div>
</td>
<td>Bitwise or</td>
</tr>
<tr><td>^</td>
<td>Bitwise xor</td>
</tr>
<tr><td>~</td>
<td>Bitwise negation</td>
</tr>
<tr><td>&lt;&lt;</td>
<td>Shift left</td>
</tr>
<tr><td>&gt;&gt;</td>
<td>Shift right</td>
</tr>
</tbody>
</table>
<p>Table 3-3: Bitwise and Conditional Operators</p>
<p>Augmented assignment operators are those that combine two or more operations into one.  While augmented assignment can assist in coding concisely, some say that too many such operators can make code more difficult to read.</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operator</th>
<th class="head">Description and Logic</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>+=</td>
<td>a = a + b</td>
</tr>
<tr><td>-=</td>
<td>a = a – b</td>
</tr>
<tr><td><a href="#id3"><span class="problematic" id="id4">*</span></a>=</td>
<td>a = a * b</td>
</tr>
<tr><td>/=</td>
<td>a = a / b</td>
</tr>
<tr><td>%=</td>
<td>a = a % b</td>
</tr>
<tr><td>//=</td>
<td>a = a // b</td>
</tr>
<tr><td><a href="#id5"><span class="problematic" id="id6">**</span></a>=</td>
<td>a = a** b</td>
</tr>
<tr><td>&amp;=</td>
<td>a = a &amp; b</td>
</tr>
<tr><td><a href="#id7"><span class="problematic" id="id8">|</span></a>=</td>
<td>a = a | b</td>
</tr>
<tr><td>^=</td>
<td>a = a ^ b</td>
</tr>
<tr><td>&gt;&gt;=</td>
<td>a = a &gt;&gt; b</td>
</tr>
<tr><td>&lt;&lt;=</td>
<td>a = a &lt;&lt; b</td>
</tr>
</tbody>
</table>
<p>Table 3-4:  Augmented Assignment Operators</p>
</div>
<div class="section" id="boolean-expressions">
<h2>Boolean Expressions<a class="headerlink" href="#boolean-expressions" title="Permalink to this headline"></a></h2>
<p>Comparing two or more values or expressions also uses a similar syntax to that of other languages, and the logic is quite the same.  Note that in Python, <em>True</em> and <em>False</em> are very similar to constants in the Java language.  <em>True</em> actually represents the number <em>1</em>, and <em>False</em> represents the number <em>0</em>.  One could just as easily code using 0 and 1 to represent the boolean values, but for readability and maintenance the <em>True</em> and <em>False</em> “constants” are preferred.  Java developers, make sure that you capitalize the first letter of these two words as you will receive an ugly <em>NameError</em> if you do not.</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="8%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Conditional</th>
<th class="head">Logic</th>
<th class="head">&nbsp;</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>and</td>
<td>&nbsp;</td>
<td>In an <em>x and y</em> evaluation, both x and y must evaluate to True</td>
</tr>
<tr><td>or</td>
<td>&nbsp;</td>
<td>In an <em>x or y</em> evaluation, if x is false then y is evaluated.</td>
</tr>
<tr><td>not</td>
<td>&nbsp;</td>
<td>In a <em>not x</em> evaluation, if <em>not x</em>, we mean the opposite of x</td>
</tr>
</tbody>
</table>
<p>Table 3-5: Boolean Conditionals</p>
</div>
<div class="section" id="conversions">
<h2>Conversions<a class="headerlink" href="#conversions" title="Permalink to this headline"></a></h2>
<p>There are a number of conversion functions built into the language in order to help conversion of one data type to another.  While every data type in Jython is actually a class object, these conversion functions will really convert one class type into another.  For the most part, the built-in conversion functions are easy to remember because they are primarily named after the type to which you are trying to convert.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">Function</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>chr(value)</td>
<td>Converts integer to a character</td>
</tr>
<tr><td>complex(real [,imag])</td>
<td>Produces a complex number</td>
</tr>
<tr><td>dict(sequence)</td>
<td>Produces a dictionary from a given sequence of (key,value) tuples</td>
</tr>
<tr><td>eval(string)</td>
<td>Evaluates a string to return an object…useful for mathematical computations</td>
</tr>
<tr><td>float(value)</td>
<td>Converts to float</td>
</tr>
<tr><td>frozenset(set)</td>
<td>Converts a set into a frozen set</td>
</tr>
<tr><td>hex(value)</td>
<td>Converts an integer into a hex string</td>
</tr>
<tr><td>int(value [, base])</td>
<td>Converts to an integer using a base if a string is given</td>
</tr>
<tr><td>list(sequence)</td>
<td>Converts a given sequence into a list</td>
</tr>
<tr><td>long(value [, base])</td>
<td>Converts to a long using a base if a string is given</td>
</tr>
<tr><td>oct(value)</td>
<td>Converts integer to octal</td>
</tr>
<tr><td>ord(value)</td>
<td>Converts a character into it’s integer value</td>
</tr>
<tr><td>repr(value)</td>
<td>Converts object into an expression string.  Same as enclosing expression in reverse quotes ( <cite>x + y</cite>)</td>
</tr>
<tr><td>set(sequence)</td>
<td>Converts a sequence into a set</td>
</tr>
<tr><td>str(value)</td>
<td>Converts an object into a string</td>
</tr>
<tr><td>tuple(sequence)</td>
<td>Converts a given sequence to a tuple</td>
</tr>
<tr><td>unichr(value)</td>
<td>Converts integer to a Unicode character</td>
</tr>
</tbody>
</table>
<p>Table 3-6:  Conversion Functions</p>
<p>The following is an example of using the <em>eval()</em> functionality as it is perhaps the one conversion function for which an example helps to understand.</p>
<div class="highlight-python"><pre># Suppose keyboard input contains an expression in string format (x * y)
&gt;&gt;&gt; x = 5
&gt;&gt;&gt; y = 12
&gt;&gt;&gt; keyboardInput = 'x * y'
&gt;&gt;&gt; eval(keyboardInput)
60</pre>
</div>
</div>
<div class="section" id="program-flow">
<h2>Program Flow<a class="headerlink" href="#program-flow" title="Permalink to this headline"></a></h2>
<p>The Python programming language has structure that sets it apart from the others.  As you’ve learned in previous references in this book, the statements that make up programs in Python are structured with attention to spacing, order, and technique.  In order to develop a statement in Python, you must adhere to proper spacing techniques throughout the code block.  Convention and good practice adhere to four spaces of indentation per statement throughout the entire program.  Follow this convention along with some control flow and you’re sure to develop some easily maintainable software.</p>
<p>The standard Python if-else conditional statement is used in order to evaluate expressions and branch program logic based upon the outcome.  Expressions that are usable in an if-else statement can consist of any operators we’ve discussed previously.  The objective is to write and compare expressions in order to evaluate to a <em>True</em> or <em>False</em> outcome.  As shown in Chapter 1, the logic for an <em>if-else</em> statement follows one path if an expression evaluates to <em>True</em>, or a different path if it evaluates to <em>False.</em></p>
<p>You can chain as many <em>if-else</em> expressions together as needed.  The combining <em>if-else</em> keyword is <em>elif</em>, which is used for every expression in between the first and the last expressions within a conditional statement.</p>
<div class="highlight-python"><pre># terminal symbols are left out of this example so that you can see the concise indentation
pi =3.14
x = 2.7 * 1.45
if x == pi:
    print ‘The number is pi’
elif x &gt; pi:
    print ‘The number is greater than pi’
else:
    print ‘The number is less than pi’</pre>
</div>
<p>Another construct that we touched upon in Chapter 1 was the loop.  Every programming language provides looping implementations, and Python is no different.  The Python language provides two main types of loops known as the <em>while</em> and the <em>for</em> loop.  The <em>while</em> loop logic follows the same semantics as the <em>while</em> loop in Java.  The loop will continue processing until the expression evaluates to <em>False</em>.  At this time the looping ends and that would be it for the Java implementation.  However, in Python the <em>while * loop construct also contains an *else</em> clause which is executed when the looping completes.</p>
<div class="highlight-python"><pre>while True:
    # perform some processing
else:
    print ‘Processing Complete…’</pre>
</div>
<p>This <em>else</em> clause can come in handy while performing intensive processing so that we can inform the user of the completion of such tasks.  It can also be handy when debugging code.  Also mentioned in Chapter 1 were the <em>break</em>, and <em>continue</em> statements.  These all come in handy when using any looping construct.  The <em>break</em> statement can be used to break out of a loop.  It should be noted that if there are nested loops then the <em>break</em> statement will break out of the inner-most loop only, the outer loops will continue to process.  The <em>continue</em> statement can be used to break out of the current processing statement and continue the loop from the beginning.  The <em>continue</em> can be thought of as a skipping statement as it will cause execution to skip all remaining statements in the block and restart from the beginning (if the loop expression still evaluates to <em>True</em> of course).</p>
<div class="highlight-python"><pre>while x != y:
    # perform some processing
    if x &lt; 0:
        break
else:
    print ‘The program executed to completion’</pre>
</div>
<p>In the example above, the program will continue to process until x does not equal y.  However, if at any point during the processing the x variable evaluates less than zero, then the execution stops.  The <em>else</em> clause will not be executed if the <em>break</em> statement is invoked.  It will only be executed under normal termination of the loop.</p>
<p>The <em>for</em> loop can be used on any iterable object.  It will simply iterate through the object and perform some processing during each pass.  Both the <em>break</em> and <em>continue</em> statements can also be used within the <em>for</em> loop.  The <em>for</em> statement in Python also differs from the same statement in Java because in Python we also have the <em>else</em> clause with this construct.  Once again, the <em>else</em> clause is executed when the <em>for</em> loop processes to completion without any <em>break</em> intervention.  Also, if you are familiar with pre-Java 5 <em>for</em> loops then you will love the Python syntax.  In Java 5, the syntax of the <em>for</em> statement was adjusted a bit to make it more in line with syntactically easy languages such as Python.</p>
<div class="highlight-python"><pre>for(x = 0; x &lt;= myList.size(); x++){
    // processing statements iterating through myList
    System.out.println(“The current index is: “ + x);
}

x = 0
for value in myList:
    # processing statements using value as the current item in myList
    print ‘The current index is %i’ % (x)
    x = x + 1</pre>
</div>
<p>As you can see, the Python syntax is a little easier to understand, but it doesn’t really save too many keystrokes at this point.  We still have to manage the index (x in this case) by ourselves by incrementing it with each iteration of the loop.  However, Python does provide a built-in function that can save us some keystrokes and provides a similar functionality to that of Java with the automatically incrementing index on the <em>for</em> loop.  The <em>enumerate(sequence)</em> function does just that.  It will provide an index for our use and automatically manage it for us.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">myList</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;jython&#39;</span><span class="p">,</span><span class="s">&#39;java&#39;</span><span class="p">,</span><span class="s">&#39;python&#39;</span><span class="p">,</span><span class="s">&#39;jruby&#39;</span><span class="p">,</span><span class="s">&#39;groovy&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">index</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">myList</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">index</span><span class="p">,</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="go">0 jython</span>
<span class="go">1 java</span>
<span class="go">2 python</span>
<span class="go">3 jruby</span>
<span class="go">4 groovy</span>
</pre></div>
</div>
<p>Now we have covered the program flow for conditionals and looping constructs in the Python language.  Note that you can next to any level, and provide as many <em>if-else</em> conditionals as you’d like.  However, good programming practice will tell you to keep it as simple as possible or the logic will become too hard to follow.</p>
</div>
<div class="section" id="example-code">
<h2>Example Code<a class="headerlink" href="#example-code" title="Permalink to this headline"></a></h2>
<p>Let’s take a look at an example program that uses some of the program flow which was discussed in this chapter.  The example program simply makes use of an external text file to manage a list of players on a sports team.  You will see how to follow proper program structure and use spacing effectively in this example.  You will also see file utilization in action, along with utiliation of the <em>raw_input()</em> function.</p>
<div class="highlight-python"><pre>playerDict = {}
saveFile = False
exitSystem = False
# Enter a loop to enter inforation from keyboard
while not exitSystem:
    print 'Sports Team Administration App'
    enterPlayer = raw_input("Would you like to create a team or manage an existing team?\n (Enter 'C' for create, 'M' for manage, 'X' to exit) ")
    if enterPlayer.upper() == 'C':
        exitSystem = False
    # Enter a player for the team
        print 'Enter a list of players on our team along with their position'
        enterCont = 'Y'
        #  While continuing to enter new players, perform the following
        while enterCont.upper() == 'Y':
            name = raw_input('Enter players first name: ')
            position = raw_input('Enter players position: ')
            playerDict[name] = position
            saveFile = True
            enterCont = raw_input("Enter another player? (Press 'N' to exit or 'Y' to continue)")
        else:
            exitSystem = True
   elif enterPlayer.upper() == 'M':
        exitSystem = False
        # Read values from the external file into a dictionary object
        print '\n’
       print 'Manage the Team'
        playerfile = open('players.txt','r')
        for player in playerfile:
            playerList = player.split(':')
            playerDict[playerList[0]] = playerList[1]
        print 'Team Listing'
        print '++++++++++++'
        for i, player in enumerate(playerDict):
            print 'Player %s Name: %s -- Position: %s' %(i, player, playerDict[player])
    else:
        exitSystem = True
else:
    # Save the external file and close resources
    if saveFile:
        print 'Saving Team Data...'
        playerfile = open('players.txt','w')
        for player in playerDict:
            playerfile.write(player + ':' + playerDict[player] + '\n')
        playerfile.close()</pre>
</div>
</div>
<div class="section" id="summary">
<h2>Summary<a class="headerlink" href="#summary" title="Permalink to this headline"></a></h2>
<p>All programs are constructed out of definitions, statements and expressions.  In this chapter we covered details of creating expressions and using them.  Expressions can be composed of any number of mathematical operators and comparisons.  In this chapter we discussed the basics of using mathematical operators in our programs.  The __future__ division topic introduced us to using features from the __future__.  We then delved into comparisons and comparison operators.</p>
<p>We ended this short chapter by discussing proper program flow and properly learned about the <em>if</em> statement as well as how to construct different types of loops in Python.  In the next chapter you will learn how to write functions, and the use of many built-in functions will be discussed.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">Chapter 3: Operators, Expressions, and Program Flow</a><ul>
<li><a class="reference external" href="#types-of-expressions">Types of Expressions</a></li>
<li><a class="reference external" href="#mathematical-operations">Mathematical Operations</a></li>
<li><a class="reference external" href="#boolean-expressions">Boolean Expressions</a></li>
<li><a class="reference external" href="#conversions">Conversions</a></li>
<li><a class="reference external" href="#program-flow">Program Flow</a></li>
<li><a class="reference external" href="#example-code">Example Code</a></li>
<li><a class="reference external" href="#summary">Summary</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="chapter2.html"
                                  title="previous chapter">Chapter 2: Data Types and Referencing</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="chapter5.html"
                                  title="next chapter">Chapter 5: Exception Handling and Debugging</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/chapter3.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="chapter5.html" title="Chapter 5: Exception Handling and Debugging"
             >next</a> |</li>
        <li class="right" >
          <a href="chapter2.html" title="Chapter 2: Data Types and Referencing"
             >previous</a> |</li>
        <li><a href="index.html">Jython Book v0.1 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2009, Josh Juneau, Frank Wierzbicki, Jim Baker, Leo Soto, ViVictor Ng.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.