-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path03-conditional.tex
747 lines (617 loc) · 20.4 KB
/
03-conditional.tex
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
% LaTeX source for ``Python for Informatics: Exploring Information''
% Copyright (c) 2010- Charles R. Severance, All Rights Reserved
\chapter{Ejecuci\'on condicional}
\section{Expresiones booleanas }
\index{boolean expression or expresiones booleanas}
\index{expression!boolean}
\index{logical operator u operador l\'ogico}
\index{operator!logical}
Una {\bf expresi\'on booleana} es una expresi\'on que es o falsa o verdadera. Los siguientes ejemplo utilizan el
operador {\tt ==}, el cual compara dos operandos y produce
{\tt True} si son iguales y {\tt False} si no lo son:
\beforeverb
\begin{verbatim}
>>> 5 == 5
True
>>> 5 == 6
False
\end{verbatim}
\afterverb
%
{\tt True} y {\tt False} son valores especiales
que pertenecen al tipo {\tt bool}; estos no son cadenas o ``strings":
\index{True special value}
\index{False special value}
\index{special value!True}
\index{special value!False}
\index{bool type}
\index{type!bool}
\beforeverb
\begin{verbatim}
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
\end{verbatim}
\afterverb
%
El operador {\tt ==} es uno de los {\bf operadores de comparaci\'on}; los
otros son:
\beforeverb
\begin{verbatim}
x != y # x no es igual a y
x > y # x es mayor que y
x < y # x es menor que y
x >= y # x es mayor o igual a y
x <= y # x es menor o igual a y
x is y # x es lo mismo que y
x is not y # x no es lo mismo que y
\end{verbatim}
\afterverb
%
Aunque estas operaciones le resulten probablemente familiares, los s\'imbolos de Python
son diferentes a los s\'imbolos matem\'aticos. Un error muy com\'un es utilizar el signo igual solo ({\tt =}) en vez del signo igual doble
({\tt ==}). Recuerde que {\tt =} es un operador para asignar valor y
{\tt ==} es un operador de comparaci\'on. No hay tal cosa como
{\tt =<} o {\tt =>}.
\index{comparison operator}
\index{operator!comparison}
\section {Operadores de l\'ogica}
\index{logical operator}
\index{operator!logical}
There are three {\bf logical operators}: {\tt and}, {\tt
or}, and {\tt not}. The semantics (meaning) of these operators is
similar to their meaning in English. For example,
{\tt x > 0 and x < 10}
is true only if {\tt x} is greater than 0
\emph{and} less than 10.
\index{and operator}
\index{or operator}
\index{not operator}
\index{operator!and}
\index{operator!or}
\index{operator!not}
{\tt n\%2 == 0 or n\%3 == 0} is true if \emph{either} of the conditions
is true, that is, if the number is divisible by 2 \emph{or} 3.
Finally, the {\tt not} operator negates a boolean
expression, so {\tt not (x > y)} is true if {\tt x > y} is false,
that is, if {\tt x} is less than or equal to {\tt y}.
Strictly speaking, the operands of the logical operators should be
boolean expressions, but Python is not very strict.
Any nonzero number is interpreted as ``true.''
\beforeverb
\begin{verbatim}
>>> 17 and True
True
\end{verbatim}
\afterverb
%
This flexibility can be useful, but there are some subtleties to
it that might be confusing. You might want to avoid it (unless
you know what you are doing).
\section{Ejecuci\'on condicional}
\label{conditional execution o ejecuci\'on condicional}
\index{conditional statement o afirmaciones condicionales}
\index{statement!conditional}
\index{if statement o condicional si}
\index{statement!if}
\index{conditional execution o ejecuci\'on condicional}
In order to write useful programs, we almost always need the ability
to check conditions and change the behavior of the program
accordingly. {\bf Conditional statements} give us this ability. The
simplest form is the {\tt if} statement:
\beforeverb
\begin{verbatim}
if x > 0 :
print 'x is positive'
\end{verbatim}
\afterverb
%
The boolean expression after the {\tt if} statement is
called the {\bf condition}. We end the {\tt if}
statement with a colon character (:) and the line(s)
after the if statement are indented.
\beforefig
\centerline{\includegraphics[height=1.75in]{figs2/if.eps}}
\afterfig
If the logical condition is true, then the indented
statement gets executed. If the logical condition is
false, the indented statement is skipped.
\index{condition}
\index{compound statement}
\index{statement!compound}
{\tt if} statements have the same structure as function definitions
or {\tt for} loops. The statement consists of a header line
that ends with the colon character (:)
followed by an indented block. Statements like this are
called {\bf compound statements} because they stretch
across more than one line.
There is no limit on the number of statements that can appear in
the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements (usually
as a place keeper for code you haven't written yet). In that
case, you can use the {\tt pass} statement, which does nothing.
\index{pass statement}
\index{statement!pass}
\beforeverb
\begin{verbatim}
if x < 0 :
pass # need to handle negative values!
\end{verbatim}
\afterverb
%
If you enter an if statement in the Python interpreter, the prompt will change
from three chevrons to three dots to indicate you are in the middle of a block of
statements as shown below:
\beforeverb
\begin{verbatim}
>>> x = 3
>>> if x < 10:
... print 'Small'
...
Small
>>>
\end{verbatim}
\afterverb
%
\section{Ejecuci\'on alternativa}
\label{alternative execution o ejecuci\'on alternativa }
\index{alternative execution o ejecuci\'on alternativa}
\index{else keyword}
\index{keyword!else}
A second form of the {\tt if} statement is {\bf alternative execution},
in which there are two possibilities and the condition determines
which one gets executed. The syntax looks like this:
\beforeverb
\begin{verbatim}
if x%2 == 0 :
print 'x is even'
else :
print 'x is odd'
\end{verbatim}
\afterverb
%
If the remainder when {\tt x} is divided by 2 is 0, then we
know that {\tt x} is even, and the program displays a message to that
effect. If the condition is false, the second set of statements is
executed.
\beforefig
\centerline{\includegraphics[height=1.75in]{figs2/if-else.eps}}
\afterfig
Since the condition must be true or false, exactly one of
the alternatives will be executed. The alternatives are called
{\bf branches}, because they are branches in the flow of execution.
\index{branch}
\section{Condicionales en cadena}
\index{chained conditional o condicionales en cadena}
\index{conditional!chained}
Sometimes there are more than two possibilities and we need more than
two branches. One way to express a computation like that is a {\bf
chained conditional}:
\beforeverb
\begin{verbatim}
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
\end{verbatim}
\afterverb
%
{\tt elif} is an abbreviation of ``else if.'' Again, exactly one
branch will be executed.
\beforefig
\centerline{\includegraphics[height=3.00in]{figs2/elif.eps}}
\afterfig
There is no limit on the number of {\tt
elif} statements. If there is an {\tt else} clause, it has to be
at the end, but there doesn't have to be one.
\index{elif keyword}
\index{keyword!elif}
\beforeverb
\begin{verbatim}
if choice == 'a':
print 'Bad guess'
elif choice == 'b':
print 'Good guess'
elif choice == 'c':
print 'Close, but not correct'
\end{verbatim}
\afterverb
%
Each condition is checked in order. If the first is false,
the next is checked, and so on. If one of them is
true, the corresponding branch executes, and the statement
ends. Even if more than one condition is true, only the
first true branch executes.
\section{Condicionales anidados}
\index{nested conditional o condicionales anidados}
\index{conditional!nested}
One conditional can also be nested within another. We could have
written the trichotomy example like this:
\beforeverb
\begin{verbatim}
if x == y:
print 'x and y are equal'
else:
if x < y:
print 'x is less than y'
else:
print 'x is greater than y'
\end{verbatim}
\afterverb
%
The outer conditional contains two branches. The
first branch contains a simple statement. The second branch
contains another {\tt if} statement, which has two branches of its
own. Those two branches are both simple statements,
although they could have been conditional statements as well.
\beforefig
\centerline{\includegraphics[height=2.50in]{figs2/nested.eps}}
\afterfig
Although the indentation of the statements makes the structure
apparent, {\bf nested conditionals} become difficult to read very
quickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the following code using a
single conditional:
\beforeverb
\begin{verbatim}
if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
\end{verbatim}
\afterverb
%
The {\tt print} statement is executed only if we make it past both
conditionals, so we can get the same effect with the {\tt and} operator:
\beforeverb
\begin{verbatim}
if 0 < x and x < 10:
print 'x is a positive single-digit number.'
\end{verbatim}
\afterverb
\section{Captaci\'on de excepciones utilizando ``try'' y ``except''}
\label{catch1}
Earlier we saw a code segment where we used the \verb"raw_input" and
{\tt int} functions to read and parse an integer number entered by
the user. We also saw how treacherous doing this could be:
\beforeverb
\begin{verbatim}
>>> 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()
>>>
\end{verbatim}
\afterverb
%
When we are executing these statements in the Python interpreter,
we get a new prompt from the interpreter, think ``oops'' and move
on to our next statement.
However if this code is placed in a
Python script and this error occurs, your script immediately
stops in its tracks with a traceback.
It does not execute the following statement.
\index{traceback}
Here is a sample program to convert a Fahrenheit temperature
to a Celsius temperature:
\index{fahrenheit}
\index{celsius}
\index{temperature conversion}
\beforeverb
\begin{verbatim}
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
\end{verbatim}
\afterverb
%
If we execute this code and give it invalid input, it simply fails
with an unfriendly error message:
\beforeverb
\begin{verbatim}
python fahren.py
Enter Fahrenheit Temperature:72
22.2222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahr = float(inp)
ValueError: invalid literal for float(): fred
\end{verbatim}
\afterverb
%
There is a conditional execution structure built into
Python to handle these types of expected and unexpected
errors called ``try / except''. The idea of {\tt try}
and {\tt except} is that you know that some sequence
of instruction(s) may have a problem and you want to
add some statements to be executed if an error occurs.
These extra statements (the except block) are ignored
if there is no error.
You can think of the {\tt try} and {\tt except} feature
in Python as an ``insurance policy'' on a sequence of
statements.
We can rewrite our temperature converter as follows:
\beforeverb
\begin{verbatim}
inp = raw_input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
except:
print 'Please enter a number'
\end{verbatim}
\afterverb
%
Python starts by executing the
sequence of statements in the
{\tt try} block. If all goes
well, it skips the {\tt except} block and proceeds. If an
exception occurs in the {\tt try} block,
Python jumps out of the {\tt try} block and
executes the sequence of statements in the {\tt except} block.
\beforeverb
\begin{verbatim}
python fahren2.py
Enter Fahrenheit Temperature:72
22.2222222222
python fahren2.py
Enter Fahrenheit Temperature:fred
Please enter a number
\end{verbatim}
\afterverb
%
Handling an exception with a {\tt try} statement is called {\bf
catching} an exception. In this example, the {\tt except} clause
prints an error message. In general,
catching an exception gives you a chance to fix the problem, or try
again, or at least end the program gracefully.
\section{Evaluaci\'on de cortocircuito de expresiones l\'ogicas}
\index{short circuit o cortocircuito}
When Python is processing a logical expression such as
{\tt x >= 2 and (x/y) > 2}, it evaluates the expression
from left-to-right. Because of the definition of {\tt and},
if {\tt x} is less than 2, the expression {\tt x >= 2} is
{\tt False} and so the whole expression is {\tt False} regardless
of whether {\tt (x/y) > 2} evaluates to {\tt True} or {\tt False}.
When Python detects that there is nothing to be gained by evaluating
the rest of a logical expression, it stops its evaluation and does
not do the computations in the rest of the logical expression.
When the evaluation of a logical expression stops because the overall
value is already known, it is called {\bf short-circuiting}
the evaluation.
\index{guardian pattern}
\index{pattern!guardian}
While this may seem like a fine point, the short circuit behavior
leads to a clever technique called the {\bf guardian pattern}.
Consider the following code sequence in the Python interpreter:
\beforeverb
\begin{verbatim}
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>>
\end{verbatim}
\afterverb
%
The third calculation failed because Python was evaluating {\tt (x/y)}
and {\tt y} was zero which causes a runtime error. But the second example
did \emph{not} fail because the first part of the expression {\tt x >= 2}
evaluated to {\tt False} so the {\tt (x/y)} was not ever executed
due to the {\bf short circuit} rule and there was no error.
We can construct the logical expression to strategically place a {\bf guard}
evaluation just before the evaluation that might cause an error as follows:
\beforeverb
\begin{verbatim}
>>> x = 1
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x >= 2 and (x/y) > 2 and y != 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>>
\end{verbatim}
\afterverb
%
In the first logical expression, {\tt x >= 2} is {\tt False} so the evaluation
stops at the {\tt and}. In the second logical expression {\tt x >= 2} is {\tt True}
but {\tt y != 0} is {\tt False} so we never reach {\tt (x/y)}.
In the third logical expression, the {\tt y != 0} is \emph{after} the
{\tt (x/y) } calculation so the expression fails with an error.
In the second expression, we say that {\tt y != 0} acts as a {\bf guard}
to insure that we only execute {\tt (x/y)} if {\tt y} is non-zero.
\section{Depuraci\'on}
\label{whitespace o espacio en blanco}
\index{debugging o depuraci\'on}
\index{traceback o rastrear}
The traceback Python displays when an error occurs contains
a lot of information, but it can be overwhelming, especially
when there are many frames on the stack. The most
useful parts are usually:
\begin{itemize}
\item What kind of error it was, and
\item Where it occurred.
\end{itemize}
Syntax errors are usually easy to find, but there are a few
gotchas. Whitespace errors can be tricky because spaces and
tabs are invisible and we are used to ignoring them.
\index{whitespace}
\beforeverb
\begin{verbatim}
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y = 6
^
SyntaxError: invalid syntax
\end{verbatim}
\afterverb
%
In this example, the problem is that the second line is indented by
one space. But the error message points to {\tt y}, which is
misleading. In general, error messages indicate where the problem was
discovered, but the actual error might be earlier in the code,
sometimes on a previous line.
\index{error!runtime}
\index{runtime error}
The same is true of runtime errors. Suppose you are trying
to compute a signal-to-noise ratio in decibels. The formula
is $SNR_{db} = 10 \log_{10} (P_{signal} / P_{noise})$. In Python,
you might write something like this:
\beforeverb
\begin{verbatim}
import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
\end{verbatim}
\afterverb
%
But when you run it, you get an error message\footnote{In Python 3.0,
you no longer get an error message; the division operator performs
floating-point division even with integer operands.}:
\index{exception!OverflowError}
\index{OverflowError}
\beforeverb
\begin{verbatim}
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
OverflowError: math range error
\end{verbatim}
\afterverb
%
The error message indicates line 5, but there is nothing
wrong with that line. To find the real error, it might be
useful to print the value of {\tt ratio}, which turns out to
be 0. The problem is in line 4, because dividing two integers
does floor division. The solution is to represent signal power
and noise power with floating-point values.
\index{floor division}
\index{division!floor}
In general, error messages tell you where the problem was discovered,
but that is often not where it was caused.
\section{Glosario}
\begin{descripci\'on}
\item[body:] The sequence of statements within a compound statement.
\index{body}
\item[boolean expression:] An expression whose value is either
{\tt True} or {\tt False}.
\index{boolean expression}
\index{expression!boolean}
\item[branch:] One of the alternative sequences of statements in
a conditional statement.
\index{branch}
\item[chained conditional:] A conditional statement with a series
of alternative branches.
\index{chained conditional}
\index{conditional!chained}
\item[comparison operator:] One of the operators that compares
its operands: {\tt ==}, {\tt !=}, {\tt >}, {\tt <}, {\tt >=}, and {\tt <=}.
\item[conditional statement:] A statement that controls the flow of
execution depending on some condition.
\index{conditional statement}
\index{statement!conditional}
\item[condition:] The boolean expression in a conditional statement
that determines which branch is executed.
\index{condition}
\item[compound statement:] A statement that consists of a header
and a body. The header ends with a colon (:). The body is indented
relative to the header.
\index{compound statement}
\item[guardian pattern:] Where we construct a logical expression
with additional
comparisons to take advantage of the short circuit behavior.
\index{guardian pattern}
\index{pattern!guardian}
\item[logical operator:] One of the operators that combines boolean
expressions: {\tt and}, {\tt or}, and {\tt not}.
\item[nested conditional:] A conditional statement that appears
in one of the branches of another conditional statement.
\index{nested conditional}
\index{conditional!nested}
\item[traceback:] A list of the functions that are executing,
printed when an exception occurs.
\index{traceback}
\item[short circuit:] When Python is part-way through evaluating a
logical expression and stops the evaluation because Python
knows the final value for the expression
without needing to evaluate the rest of the expression.
\index{short circuit}
\end{description}
\section{Ejercicios}
\begin{ex}
Rewrite your pay computation to give the employee 1.5
times the hourly rate for
hours worked above 40 hours.
\begin{verbatim}
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
\end{verbatim}
\end{ex}
\begin{ex}
Rewrite your pay program using {\tt try} and {\tt except}
so that your program handles non-numeric input gracefully
by printing a message and exiting the program.
The following shows two executions of the program:
\begin{verbatim}
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
\end{verbatim}
\end{ex}
\begin{ex}
Write a program to prompt for a score between 0.0 and 1.0.
If the score is out of range print an error. If the score
is between 0.0 and 1.0, print a grade using the following
table:
\begin{verbatim}
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Enter score: 0.95
A
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
\end{verbatim}
Run the program repeatedly as shown above to test the
various different values for input.
\end{ex}