- Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathConditionalStatements.html
586 lines (541 loc) · 53.2 KB
/
ConditionalStatements.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
<!DOCTYPE html>
<htmlclass="writer-html5" lang="en" >
<head>
<metacharset="utf-8" /><metacontent="Topic: Conditional Statements, Difficulty: Easy, Category: Section" name="description" />
<metacontent="if, else, elif, inline if, switch statement, comparison operator, bool, truth, is operator" name="keywords" />
<metaname="viewport" content="width=device-width, initial-scale=1.0" />
<title>Conditional Statements — Python Like You Mean It</title>
<linkrel="stylesheet" href="../_static/pygments.css" type="text/css" />
<linkrel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<linkrel="stylesheet" href="../_static/my_theme.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../_static/js/html5shiv.min.js"></script>
<![endif]-->
<scriptdata-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<scriptsrc="../_static/jquery.js"></script>
<scriptsrc="../_static/underscore.js"></script>
<scriptsrc="../_static/doctools.js"></script>
<scriptasync="async" src="https://www.googletagmanager.com/gtag/js?id=UA-115029372-1"></script>
<scriptsrc="../_static/gtag.js"></script>
<scriptcrossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script>window.MathJax={"tex": {"inlineMath": [["$","$"],["\\(","\\)"]],"processEscapes": true},"options": {"ignoreHtmlClass": "tex2jax_ignore|mathjax_ignore|document","processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<scriptdefer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<scriptsrc="../_static/js/theme.js"></script>
<linkrel="index" title="Index" href="../genindex.html" />
<linkrel="search" title="Search" href="../search.html" />
<linkrel="next" title="For-Loops and While-Loops" href="ForLoops.html" />
<linkrel="prev" title="Introducing Control Flow" href="Introduction.html" />
</head>
<bodyclass="wy-body-for-nav">
<divclass="wy-grid-for-nav">
<navdata-toggle="wy-nav-shift" class="wy-nav-side">
<divclass="wy-side-scroll">
<divclass="wy-side-nav-search" >
<ahref="../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<divclass="version">
1.4
</div>
<divrole="search">
<formid="rtd-search-form" class="wy-form" action="../search.html" method="get">
<inputtype="text" name="q" placeholder="Search docs" />
<inputtype="hidden" name="check_keywords" value="yes" />
<inputtype="hidden" name="area" value="default" />
</form>
</div>
</div><divclass="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<pclass="caption" role="heading"><spanclass="caption-text">Table of Contents:</span></p>
<ulclass="current">
<liclass="toctree-l1"><aclass="reference internal" href="../intro.html">Python Like You Mean It</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_1.html">Module 1: Getting Started with Python</a></li>
<liclass="toctree-l1 current"><aclass="reference internal" href="../module_2.html">Module 2: The Essentials of Python</a><ulclass="current">
<liclass="toctree-l2"><aclass="reference internal" href="Basic_Objects.html">Basic Object Types</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="SequenceTypes.html">Sequence Types</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Variables_and_Assignment.html">Variables & Assignment</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Introduction.html">Introducing Control Flow</a></li>
<liclass="toctree-l2 current"><aclass="current reference internal" href="#">Conditional Statements</a><ul>
<liclass="toctree-l3"><aclass="reference internal" href="#Comparison-Operations">Comparison Operations</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#bool-and-Truth-Values-of-Non-Boolean-Objects"><codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code> and Truth Values of Non-Boolean Objects</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#if,-else,-and-elif"><codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code></a><ul>
<liclass="toctree-l4"><aclass="reference internal" href="#Inline-if-else-statements">Inline if-else statements</a></li>
</ul>
</li>
<liclass="toctree-l3"><aclass="reference internal" href="#Short-Circuiting-Logical-Expressions">Short-Circuiting Logical Expressions</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#Links-to-Official-Documentation">Links to Official Documentation</a></li>
<liclass="toctree-l3"><aclass="reference internal" href="#Reading-Comprehension-Exercise-Solutions:">Reading Comprehension Exercise Solutions:</a></li>
</ul>
</li>
<liclass="toctree-l2"><aclass="reference internal" href="ForLoops.html">For-Loops and While-Loops</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Iterables.html">Iterables</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Generators_and_Comprehensions.html">Generators & Comprehension Expressions</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Itertools.html">Python’s “Itertools”</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Functions.html">Basics of Functions</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="Scope.html">Scope</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures.html">Data Structures (Part I): Introduction</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures_II_Dictionaries.html">Data Structures (Part II): Dictionaries</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DataStructures_III_Sets_and_More.html">Data Structures (Part III): Sets & the Collections Module</a></li>
</ul>
</li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_2_problems.html">Module 2: Problems</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_3.html">Module 3: The Essentials of NumPy</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_3_problems.html">Module 3: Problems</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_4.html">Module 4: Object Oriented Programming</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../module_5.html">Module 5: Odds and Ends</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../changes.html">Changelog</a></li>
</ul>
</div>
</div>
</nav>
<sectiondata-toggle="wy-nav-shift" class="wy-nav-content-wrap"><navclass="wy-nav-top" aria-label="Mobile navigation menu" >
<idata-toggle="wy-nav-top" class="fa fa-bars"></i>
<ahref="../index.html">Python Like You Mean It</a>
</nav>
<divclass="wy-nav-content">
<divclass="rst-content">
<divrole="navigation" aria-label="Page navigation">
<ulclass="wy-breadcrumbs">
<li><ahref="../index.html" class="icon icon-home"></a> »</li>
<li><ahref="../module_2.html">Module 2: The Essentials of Python</a> »</li>
<li>Conditional Statements</li>
<liclass="wy-breadcrumbs-aside">
<ahref="../_sources/Module2_EssentialsOfPython/ConditionalStatements.md.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<divrole="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<divitemprop="articleBody">
<style>
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast.container,
.nboutput.nblast.container {
margin-bottom:19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast.container+ .nbinput.container {
margin-top:-19px;
}
.admonition>p:before {
margin-right:4px; /* make room for the exclamation icon */
}
/* Fix math alignment, see https://github.com/rtfd/sphinx_rtd_theme/pull/686 */
.math {
text-align: unset;
}
</style>
<divclass="section" id="Conditional-Statements">
<h1>Conditional Statements<aclass="headerlink" href="#Conditional-Statements" title="Permalink to this headline"></a></h1>
<divclass="admonition warning">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Note</strong>:</p>
<p>There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.</p>
</div>
<p>In this section, we will be introduced to the <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code> statements. These allow you to specify that blocks of code are to be executed only if specified conditions are found to be true, or perhaps alternative code if the condition is found to be false. For example, the following code will square <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> if it is a negative number, and will cube <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> if it is a positive number:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># a simple if-else block</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o"><</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="o">**</span><spanclass="mi">2</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="o">**</span><spanclass="mi">3</span>
</pre></div>
</div>
<p>Please refer to the “Basic Python Object Types” subsection to recall the basics of the “boolean” type, which represents True and False values. We will extend that discussion by introducing comparison operations and membership-checking, and then expanding on the utility of the built-in <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code> type.</p>
<divclass="section" id="Comparison-Operations">
<h2>Comparison Operations<aclass="headerlink" href="#Comparison-Operations" title="Permalink to this headline"></a></h2>
<p>Comparison statements will evaluate explicitly to either of the boolean-objects: <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> or <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code>. There are eight comparison operations in Python:</p>
<tableclass="docutils align-default">
<colgroup>
<colstyle="width: 32%" />
<colstyle="width: 68%" />
</colgroup>
<thead>
<trclass="row-odd"><thclass="head"><p>Operation</p></th>
<thclass="head"><p>Meaning</p></th>
</tr>
</thead>
<tbody>
<trclass="row-even"><td><p><codeclass="docutils literal notranslate"><spanclass="pre"><</span></code></p></td>
<td><p>strictly less than</p></td>
</tr>
<trclass="row-odd"><td><p><codeclass="docutils literal notranslate"><spanclass="pre"><=</span></code></p></td>
<td><p>less than or equal</p></td>
</tr>
<trclass="row-even"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">></span></code></p></td>
<td><p>strictly greater than</p></td>
</tr>
<trclass="row-odd"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">>=</span></code></p></td>
<td><p>greater than or equal</p></td>
</tr>
<trclass="row-even"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">==</span></code></p></td>
<td><p>equal</p></td>
</tr>
<trclass="row-odd"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">!=</span></code></p></td>
<td><p>not equal</p></td>
</tr>
<trclass="row-even"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">is</span></code></p></td>
<td><p>object identity</p></td>
</tr>
<trclass="row-odd"><td><p><codeclass="docutils literal notranslate"><spanclass="pre">is</span><spanclass="pre">not</span></code></p></td>
<td><p>negated object identity</p></td>
</tr>
</tbody>
</table>
<p>The first six of these operators are familiar from mathematics:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="mi">2</span><spanclass="o"><</span><spanclass="mi">3</span>
<spanclass="go">True</span>
</pre></div>
</div>
<p>Note that <codeclass="docutils literal notranslate"><spanclass="pre">=</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">==</span></code> have very different meanings. The former is the assignment operator, and the latter is the equality operator:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">=</span><spanclass="mi">3</span><spanclass="c1"># assign the value 3 to the variable `x`</span>
<spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">==</span><spanclass="mi">3</span><spanclass="c1"># check if `x` and 3 have the same value</span>
<spanclass="go">True</span>
</pre></div>
</div>
<p>Python allows you to chain comparison operators to create “compound” comparisons:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="mi">2</span><spanclass="o"><</span><spanclass="mi">3</span><spanclass="o"><</span><spanclass="mi">1</span><spanclass="c1"># performs (2 < 3) and (3 < 1)</span>
<spanclass="go">False</span>
</pre></div>
</div>
<p>Whereas <codeclass="docutils literal notranslate"><spanclass="pre">==</span></code> checks to see if two objects have the same value, the <codeclass="docutils literal notranslate"><spanclass="pre">is</span></code> operator checks to see if two objects are actually the <em>same</em> object. For example, creating two lists with the same contents produces two <em>distinct</em> lists, that have the same “value”:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating `==` vs `is`</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">y</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">,</span><spanclass="mi">3</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">==</span><spanclass="n">y</span>
<spanclass="kc">True</span>
<spanclass="c1"># `x` and `y` reference equivalent, but distinct lists</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="ow">is</span><spanclass="n">y</span>
<spanclass="kc">False</span>
</pre></div>
</div>
<p>Thus the <codeclass="docutils literal notranslate"><spanclass="pre">is</span></code> operator is most commonly used to check if a variable references the <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code> object, or either of the boolean objects:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="o">=</span><spanclass="kc">None</span>
<spanclass="gp">>>> </span><spanclass="n">x</span><spanclass="ow">is</span><spanclass="kc">None</span>
<spanclass="go">True</span>
<spanclass="go"># (2 < 0) returns the object `False`</span>
<spanclass="go"># thus this becomes: `False is False`</span>
<spanclass="gp">>>> </span><spanclass="p">(</span><spanclass="mi">2</span><spanclass="o"><</span><spanclass="mi">0</span><spanclass="p">)</span><spanclass="ow">is</span><spanclass="kc">False</span>
<spanclass="go">True</span>
</pre></div>
</div>
<p>Use <codeclass="docutils literal notranslate"><spanclass="pre">is</span><spanclass="pre">not</span></code> to check if two objects are distinct:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="mi">1</span><spanclass="ow">is</span><spanclass="ow">not</span><spanclass="kc">None</span>
<spanclass="go">True</span>
</pre></div>
</div>
</div>
<divclass="section" id="bool-and-Truth-Values-of-Non-Boolean-Objects">
<h2><codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code> and Truth Values of Non-Boolean Objects<aclass="headerlink" href="#bool-and-Truth-Values-of-Non-Boolean-Objects" title="Permalink to this headline"></a></h2>
<p>Recall that the two boolean objects <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> formally belong to the <codeclass="docutils literal notranslate"><spanclass="pre">int</span></code> type in addition to <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code>, and are associated with the values <codeclass="docutils literal notranslate"><spanclass="pre">1</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">0</span></code>, respectively:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="kc">True</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">)</span>
<spanclass="go">True</span>
<spanclass="gp">>>> </span><spanclass="nb">int</span><spanclass="p">(</span><spanclass="kc">True</span><spanclass="p">)</span>
<spanclass="go">1</span>
<spanclass="gp">>>> </span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="kc">False</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">)</span>
<spanclass="go">True</span>
<spanclass="gp">>>> </span><spanclass="nb">int</span><spanclass="p">(</span><spanclass="kc">False</span><spanclass="p">)</span>
<spanclass="go">0</span>
<spanclass="gp">>>> </span><spanclass="mi">3</span><spanclass="o">*</span><spanclass="kc">True</span><spanclass="o">-</span><spanclass="kc">False</span>
<spanclass="go">3</span>
<spanclass="gp">>>> </span><spanclass="kc">True</span><spanclass="o">/</span><spanclass="kc">False</span>
<spanclass="go">---------------------------------------------------------------------------</span>
<spanclass="go">ZeroDivisionError Traceback (most recent call last)</span>
<spanclass="go"><ipython-input-4-f8487d9d0863> in <module>()</span>
<spanclass="go">----> 1 True / False</span>
<spanclass="go">ZeroDivisionError: division by zero</span>
</pre></div>
</div>
<p>Likewise Python ascribes boolean values to non-boolean objects. For example,the number 0 is associated with <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> and non-zero numbers are associated with <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>. The boolean values of built-in objects can be evaluated with the built-in Python command <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># Using `bool` to access the True/False</span>
<spanclass="c1"># value of non-boolean objects</span>
<spanclass="o">>>></span><spanclass="nb">bool</span><spanclass="p">(</span><spanclass="mi">0</span><spanclass="p">)</span>
<spanclass="kc">False</span>
</pre></div>
</div>
<p>and non-zero Python integers are associated with <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># nonzero values evaluate to `True`</span>
<spanclass="o">>>></span><spanclass="nb">bool</span><spanclass="p">(</span><spanclass="mi">2</span><spanclass="p">)</span>
<spanclass="kc">True</span>
</pre></div>
</div>
<p>The following built-in Python objects evaluate to <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> via <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code>:</p>
<ulclass="simple">
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">False</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">None</span></code></p></li>
<li><p>Zero of any numeric type: <codeclass="docutils literal notranslate"><spanclass="pre">0</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">0.0</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">0j</span></code></p></li>
<li><p>Any empty sequence, such as an empty string or list: <codeclass="docutils literal notranslate"><spanclass="pre">''</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">tuple()</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">[]</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">numpy.array([])</span></code></p></li>
<li><p>Empty dictionaries and sets</p></li>
</ul>
<p>Thus non-zero numbers and non-empty sequences/collections evaluate to <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> via <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code>.</p>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Takeaway</strong>:</p>
<p>The <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code> function allows you to evaluate the boolean values ascribed to various non-boolean objects. For instance, <codeclass="docutils literal notranslate"><spanclass="pre">bool([])</span></code> returns <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> wherease <codeclass="docutils literal notranslate"><spanclass="pre">bool([1,</span><spanclass="pre">2])</span></code> returns <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>.</p>
</div>
</div>
<divclass="section" id="if,-else,-and-elif">
<h2><codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code><aclass="headerlink" href="#if,-else,-and-elif" title="Permalink to this headline"></a></h2>
<p>We now introduce the simple, but powerful <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code> conditional statements. This will allow us to create simple branches in our code. For instance, suppose you are writing code for a video game, and you want to update a character’s status based on her/his number of health-points (an integer). The following code is representative of this:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">if</span><spanclass="n">num_health</span><spanclass="o">></span><spanclass="mi">80</span><spanclass="p">:</span>
<spanclass="n">status</span><spanclass="o">=</span><spanclass="s2">"good"</span>
<spanclass="k">elif</span><spanclass="n">num_health</span><spanclass="o">></span><spanclass="mi">50</span><spanclass="p">:</span>
<spanclass="n">status</span><spanclass="o">=</span><spanclass="s2">"okay"</span>
<spanclass="k">elif</span><spanclass="n">num_health</span><spanclass="o">></span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="n">status</span><spanclass="o">=</span><spanclass="s2">"danger"</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">status</span><spanclass="o">=</span><spanclass="s2">"dead"</span>
</pre></div>
</div>
<p>Each <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code>, and <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code> statement must end in a colon character, and the body of each of these statements is <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Introduction.html#Python-Uses-Whitespace-to-Delimit-Scope">delimited by whitespace</a>.</p>
<p>The following pseudo-code demonstrates the general template for conditional statements:</p>
<divclass="highlight-none notranslate"><divclass="highlight"><pre><span></span>if <expression_1>:
the code within this indented block is executed if..
- bool(<expression_1>) is True
elif <expression_2>:
the code within this indented block is executed if..
- bool(<expression_1>) was False
- bool(<expression_2>) is True
...
...
elif <expression_n>:
the code within this indented block is executed if..
- bool(<expression_1>) was False
- bool(<expression_2>) was False
...
...
- bool(<expression_n-1>) was False
- bool(<expression_n>) is True
else:
the code within this indented block is executed only if
all preceding expressions were False
</pre></div>
</div>
<p>In practice this can look like:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">,</span><spanclass="mi">2</span><spanclass="p">]</span>
<spanclass="k">if</span><spanclass="mi">3</span><spanclass="o"><</span><spanclass="nb">len</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">):</span>
<spanclass="c1"># bool(3 < 2) returns False, this code</span>
<spanclass="c1"># block is skipped</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"`x` has more than three items in it"</span><spanclass="p">)</span>
<spanclass="k">elif</span><spanclass="nb">len</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">)</span><spanclass="o">==</span><spanclass="mi">2</span><spanclass="p">:</span>
<spanclass="c1"># bool(len(x) == 2) returns True</span>
<spanclass="c1"># this code block is executed</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"`x` has two items in it"</span><spanclass="p">)</span>
<spanclass="k">elif</span><spanclass="nb">len</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">)</span><spanclass="o">==</span><spanclass="mi">1</span><spanclass="p">:</span>
<spanclass="c1"># this statement is never reached</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"`x` has one items in it"</span><spanclass="p">)</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="c1"># this statement is never reached</span>
<spanclass="nb">print</span><spanclass="p">(</span><spanclass="s2">"`x` is an empty list"</span><spanclass="p">)</span>
<spanclass="s2">"`x` has two items in it"</span>
</pre></div>
</div>
<p>In its simplest form, a conditional statement requires only an <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> clause. <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code> clauses can only follow an <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> clause.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># A conditional statement consisting of</span>
<spanclass="c1"># an "if"-clause, only.</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">1</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o"><</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="o">**</span><spanclass="mi">2</span>
<spanclass="c1"># x is now 1</span>
</pre></div>
</div>
<p>Similarly, conditional statements can have an <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> and an <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code> without an <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># A conditional statement consisting of</span>
<spanclass="c1"># an "if"-clause and an "else"</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="mi">4</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o">></span><spanclass="mi">2</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="o">-</span><spanclass="mi">2</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="o">+</span><spanclass="mi">1</span>
<spanclass="c1"># x is now -2</span>
</pre></div>
</div>
<p>Conditional statements can also have an <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> and an <codeclass="docutils literal notranslate"><spanclass="pre">elif</span></code> without an <codeclass="docutils literal notranslate"><spanclass="pre">else</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># A conditional statement consisting of</span>
<spanclass="c1"># an "if"-clause and an "elif"</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="s1">'abc'</span>
<spanclass="k">if</span><spanclass="nb">len</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">)</span><spanclass="o"><</span><spanclass="mi">9</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="n">x</span><spanclass="o">*</span><spanclass="mi">3</span>
<spanclass="k">elif</span><spanclass="nb">len</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">)</span><spanclass="o">></span><spanclass="mi">40</span><spanclass="p">:</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="s1">'cba'</span>
<spanclass="c1"># x is now 'abcabcabc'</span>
</pre></div>
</div>
<p>Note that only one code block within a single if-elif-else statement can be executed: either the “if-block” is executed, or an “elif-block” is executed, or the “else-block” is executed. Consecutive if-statements, however, are completely independent of one another, and thus their code blocks can be executed in sequence, if their respective conditional statements resolve to <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># consecutive if-statements are independent</span>
<spanclass="n">x</span><spanclass="o">=</span><spanclass="mi">5</span>
<spanclass="n">y</span><spanclass="o">=</span><spanclass="mi">0</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o"><</span><spanclass="mi">10</span><spanclass="p">:</span>
<spanclass="n">y</span><spanclass="o">+=</span><spanclass="mi">1</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o"><</span><spanclass="mi">20</span><spanclass="p">:</span>
<spanclass="n">y</span><spanclass="o">+=</span><spanclass="mi">1</span>
<spanclass="c1"># y is now 2</span>
</pre></div>
</div>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: Conditional statements</strong></p>
<olclass="arabic simple">
<li><p>Assume <codeclass="docutils literal notranslate"><spanclass="pre">my_list</span></code> is a list. Given the following code:</p></li>
</ol>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">first_item</span><spanclass="o">=</span><spanclass="kc">None</span>
<spanclass="k">if</span><spanclass="n">my_list</span><spanclass="p">:</span>
<spanclass="n">first_item</span><spanclass="o">=</span><spanclass="n">my_list</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span>
</pre></div>
</div>
<p>What will happen if <codeclass="docutils literal notranslate"><spanclass="pre">my_list</span></code> is <codeclass="docutils literal notranslate"><spanclass="pre">[]</span></code>? Will <codeclass="docutils literal notranslate"><spanclass="pre">IndexError</span></code> be raised? What will <codeclass="docutils literal notranslate"><spanclass="pre">first_item</span></code> be?</p>
<olclass="arabic simple" start="2">
<li><p>Assume variable <codeclass="docutils literal notranslate"><spanclass="pre">my_file</span></code> is a string storing a filename, where a period denotes the end of the filename and the beginning of the file-type. Write code that extracts only the filename.</p></li>
</ol>
<p><codeclass="docutils literal notranslate"><spanclass="pre">my_file</span></code> will have at most one period in it. Accommodate cases where <codeclass="docutils literal notranslate"><spanclass="pre">my_file</span></code> does <em>not</em> include a file-type.</p>
<p>That is:</p>
<ulclass="simple">
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">"code.py"</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">"code"</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">"doc2.pdf"</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">"doc2"</span></code></p></li>
<li><p><codeclass="docutils literal notranslate"><spanclass="pre">"hello_world"</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">"hello_world"</span></code></p></li>
</ul>
</div>
<divclass="section" id="Inline-if-else-statements">
<h3>Inline if-else statements<aclass="headerlink" href="#Inline-if-else-statements" title="Permalink to this headline"></a></h3>
<p>Python supports a syntax for writing a restricted version of if-else statements in a single line. The following code:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">num</span><spanclass="o">=</span><spanclass="mi">2</span>
<spanclass="k">if</span><spanclass="n">num</span><spanclass="o">>=</span><spanclass="mi">0</span><spanclass="p">:</span>
<spanclass="n">sign</span><spanclass="o">=</span><spanclass="s2">"positive"</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">sign</span><spanclass="o">=</span><spanclass="s2">"negative"</span>
</pre></div>
</div>
<p>can be written in a single line as:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">sign</span><spanclass="o">=</span><spanclass="s2">"positive"</span><spanclass="k">if</span><spanclass="n">num</span><spanclass="o">>=</span><spanclass="mi">0</span><spanclass="k">else</span><spanclass="s2">"negative"</span>
</pre></div>
</div>
<p>This is suggestive of the general underlying syntax for inline if-else statements:</p>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>The inline if-else statement</strong>:</p>
<p>The expression <codeclass="docutils literal notranslate"><spanclass="pre">A</span><spanclass="pre">if</span><spanclass="pre"><condition></span><spanclass="pre">else</span><spanclass="pre">B</span></code> returns <codeclass="docutils literal notranslate"><spanclass="pre">A</span></code> if <codeclass="docutils literal notranslate"><spanclass="pre">bool(<condition>)</span></code> evaluates to <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>, otherwise this expression will return <codeclass="docutils literal notranslate"><spanclass="pre">B</span></code>.</p>
</div>
<p>This syntax is highly restricted compared to the full “if-elif-else” expressions - no “elif” statement is permitted by this inline syntax, nor are multi-line code blocks within the if/else clauses.</p>
<p>Inline if-else statements can be used anywhere, not just on the right side of an assignment statement, and can be quite convenient:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># using inline if-else statements in different scenarios</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="mi">2</span>
<spanclass="c1"># will store 1 if `x` is non-negative</span>
<spanclass="c1"># will store 0 if `x` is negative</span>
<spanclass="o">>>></span><spanclass="n">my_list</span><spanclass="o">=</span><spanclass="p">[</span><spanclass="mi">1</span><spanclass="k">if</span><spanclass="n">x</span><spanclass="o">>=</span><spanclass="mi">0</span><spanclass="k">else</span><spanclass="mi">0</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="n">my_list</span>
<spanclass="p">[</span><spanclass="mi">1</span><spanclass="p">]</span>
<spanclass="o">>>></span><spanclass="s2">"a"</span><spanclass="k">if</span><spanclass="n">x</span><spanclass="o">==</span><spanclass="mi">1</span><spanclass="k">else</span><spanclass="s2">"b"</span>
<spanclass="s1">'b'</span>
</pre></div>
</div>
<p>We will see this syntax shine when we learn about comprehension statements. That being said, this syntax should be used judiciously. For example, inline if-else statements ought not be used in arithmetic expressions, for therein lies madness:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># don't ever do this...ever!</span>
<spanclass="mi">2</span><spanclass="o">-</span><spanclass="mi">3</span><spanclass="k">if</span><spanclass="n">x</span><spanclass="o"><</span><spanclass="mi">1</span><spanclass="k">else</span><spanclass="mi">1</span><spanclass="o">+</span><spanclass="mi">6</span><spanclass="o">*</span><spanclass="mi">2</span><spanclass="k">if</span><spanclass="n">x</span><spanclass="o">>=</span><spanclass="mi">0</span><spanclass="k">else</span><spanclass="mi">9</span>
</pre></div>
</div>
</div>
</div>
<divclass="section" id="Short-Circuiting-Logical-Expressions">
<h2>Short-Circuiting Logical Expressions<aclass="headerlink" href="#Short-Circuiting-Logical-Expressions" title="Permalink to this headline"></a></h2>
<p>Armed with our newfound understanding of conditional statements, we briefly return to our discussion of Python’s logic expressions to discuss “short-circuiting”. In Python, a logical expression is evaluated from left to right and will return its boolean value as soon as it is unambiguously determined, <em>leaving any remaining portions of the expression unevaluated</em>. That is, the expression may be <em>short-circuited</em>.</p>
<p>For example, consider the fact that an <codeclass="docutils literal notranslate"><spanclass="pre">and</span></code> operation will only return <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> if both of its arguments evaluate to <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code>. Thus the expression <codeclass="docutils literal notranslate"><spanclass="pre">False</span><spanclass="pre">and</span><spanclass="pre"><anything></span></code> is guaranteed to return <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code>; furthermore, when executed, this expression will return <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code><em>without having evaluated</em><codeclass="docutils literal notranslate"><spanclass="pre">bool(<anything>)</span></code>.</p>
<p>To demonstrate this behavior, consider the following example:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># demonstrating short-circuited logic expressions</span>
<spanclass="o">>>></span><spanclass="kc">False</span><spanclass="ow">and</span><spanclass="mi">1</span><spanclass="o">/</span><spanclass="mi">0</span><spanclass="c1"># evaluating `1/0` would raise an error</span>
<spanclass="kc">False</span>
</pre></div>
</div>
<p>According to our discussion, the pattern <codeclass="docutils literal notranslate"><spanclass="pre">False</span><spanclass="pre">and</span></code> short-circuits this expression without it ever evaluating <codeclass="docutils literal notranslate"><spanclass="pre">bool(1/0)</span></code>. Reversing the ordering of the arguments makes this clear.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># expressions are evaluated from left to right</span>
<spanclass="o">>>></span><spanclass="mi">1</span><spanclass="o">/</span><spanclass="mi">0</span><spanclass="ow">and</span><spanclass="kc">False</span>
<spanclass="o">---------------------------------------------------------------------------</span>
<spanclass="ne">ZeroDivisionError</span><spanclass="n">Traceback</span><spanclass="p">(</span><spanclass="n">most</span><spanclass="n">recent</span><spanclass="n">call</span><spanclass="n">last</span><spanclass="p">)</span>
<spanclass="o"><</span><spanclass="n">ipython</span><spanclass="o">-</span><spanclass="nb">input</span><spanclass="o">-</span><spanclass="mi">1</span><spanclass="o">-</span><spanclass="mi">3471672109</span><spanclass="n">ee</span><spanclass="o">></span><spanclass="ow">in</span><spanclass="o"><</span><spanclass="n">module</span><spanclass="o">></span><spanclass="p">()</span>
<spanclass="o">----></span><spanclass="mi">1</span><spanclass="mi">1</span><spanclass="o">/</span><spanclass="mi">0</span><spanclass="ow">and</span><spanclass="kc">False</span>
<spanclass="ne">ZeroDivisionError</span><spanclass="p">:</span><spanclass="n">division</span><spanclass="n">by</span><spanclass="n">zero</span>
</pre></div>
</div>
<p>In practice, short-circuiting can be leveraged in order to condense one’s code. Suppose a section of our code is processing a variable <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code>, which may be either a <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Number-Types">number</a> or a <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html#Strings">string</a>. Suppose further that we want to process <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> in a special way if it is an all-uppercased string. The code</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># this will raise an error if `x` is not a string</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o">.</span><spanclass="n">isupper</span><spanclass="p">():</span>
<spanclass="c1"># do something with the uppercased string</span>
</pre></div>
</div>
<p>is problematic because <codeclass="docutils literal notranslate"><spanclass="pre">isupper</span></code> can only be called once we are sure that <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is a string; this code will raise an error if <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is a number. We could instead write</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># a valid but messy way to filter out non-string objects</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o">.</span><spanclass="n">isupper</span><spanclass="p">():</span>
<spanclass="c1"># do something with the uppercased string</span>
</pre></div>
</div>
<p>but the more elegant and concise way of handling the nestled checking is to leverage our ability to short-circuit logic expressions.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># utilizing short-circuiting to concisely perform all necessary checks</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">)</span><spanclass="ow">and</span><spanclass="n">x</span><spanclass="o">.</span><spanclass="n">isupper</span><spanclass="p">():</span>
<spanclass="c1"># do something with the uppercased string</span>
</pre></div>
</div>
<p>See, that if <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is not a string, that <codeclass="docutils literal notranslate"><spanclass="pre">isinstance(x,</span><spanclass="pre">str)</span></code> will return <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code>; thus <codeclass="docutils literal notranslate"><spanclass="pre">isinstance(x,</span><spanclass="pre">str)</span><spanclass="pre">and</span><spanclass="pre">x.isupper()</span></code> will short-circuit and return <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> without ever evaluating <codeclass="docutils literal notranslate"><spanclass="pre">bool(x.isupper())</span></code>. This is the preferable way to handle this sort of checking. This code is more concise and readable than the equivalent nested if-statements.</p>
<divclass="admonition note">
<pclass="admonition-title fa fa-exclamation-circle"><strong>Reading Comprehension: short-circuited expressions</strong></p>
<p>Consider the preceding example of short-circuiting, where we want to catch the case where <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is an uppercased string. What is the “bug” in the following code? Why does this fail to utilize short-circuiting correctly?</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># what is wrong with me?</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o">.</span><spanclass="n">isupper</span><spanclass="p">()</span><spanclass="ow">and</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span>
<spanclass="c1"># do something with the uppercased string</span>
</pre></div>
</div>
</div>
</div>
<divclass="section" id="Links-to-Official-Documentation">
<h2>Links to Official Documentation<aclass="headerlink" href="#Links-to-Official-Documentation" title="Permalink to this headline"></a></h2>
<ulclass="simple">
<li><p><aclass="reference external" href="https://docs.python.org/3/library/functions.html#bool">bool</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing">Truth testing</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not">Boolean operations</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/library/stdtypes.html#comparisons">Comparisons</a></p></li>
<li><p><aclass="reference external" href="https://docs.python.org/3/reference/compound_stmts.html#the-if-statement">‘if’ statements</a></p></li>
</ul>
</div>
<divclass="section" id="Reading-Comprehension-Exercise-Solutions:">
<h2>Reading Comprehension Exercise Solutions:<aclass="headerlink" href="#Reading-Comprehension-Exercise-Solutions:" title="Permalink to this headline"></a></h2>
<p><strong>Conditional statements</strong></p>
<olclass="arabic simple">
<li><p>If <codeclass="docutils literal notranslate"><spanclass="pre">my_list</span></code> is <codeclass="docutils literal notranslate"><spanclass="pre">[]</span></code>, then <codeclass="docutils literal notranslate"><spanclass="pre">bool(my_list)</span></code> will return <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code>, and the code block will be skipped. Thus <codeclass="docutils literal notranslate"><spanclass="pre">first_item</span></code> will be <codeclass="docutils literal notranslate"><spanclass="pre">None</span></code>.</p></li>
<li><p>First, check to see if <codeclass="docutils literal notranslate"><spanclass="pre">.</span></code> is even contained in <codeclass="docutils literal notranslate"><spanclass="pre">my_file</span></code>. If it is, find its index-position, and slice the string up to that index. Otherwise, <codeclass="docutils literal notranslate"><spanclass="pre">my_file</span></code> is already the file name.</p></li>
</ol>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">my_file</span><spanclass="o">=</span><spanclass="s2">"code.pdf"</span>
<spanclass="k">if</span><spanclass="s2">"."</span><spanclass="ow">in</span><spanclass="n">my_file</span><spanclass="p">:</span>
<spanclass="n">dot_index</span><spanclass="o">=</span><spanclass="n">my_file</span><spanclass="o">.</span><spanclass="n">index</span><spanclass="p">(</span><spanclass="s2">"."</span><spanclass="p">)</span>
<spanclass="n">filename</span><spanclass="o">=</span><spanclass="n">my_file</span><spanclass="p">[:</span><spanclass="n">dot_index</span><spanclass="p">]</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="n">filename</span><spanclass="o">=</span><spanclass="n">my_file</span>
</pre></div>
</div>
<p><strong>Short-circuited expressions</strong></p>
<p>The code</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># what is wrong with me?</span>
<spanclass="k">if</span><spanclass="n">x</span><spanclass="o">.</span><spanclass="n">isupper</span><spanclass="p">()</span><spanclass="ow">and</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span>
<spanclass="c1"># do something with the uppercased string</span>
</pre></div>
</div>
<p>fails to account for the fact that expressions are always evaluated from left to right. That is, <codeclass="docutils literal notranslate"><spanclass="pre">bool(x.isupper())</span></code> will always be evaluated first in this instance and will raise an error if <codeclass="docutils literal notranslate"><spanclass="pre">x</span></code> is not a string. Thus the following <codeclass="docutils literal notranslate"><spanclass="pre">isinstance(x,</span><spanclass="pre">str)</span></code> statement is useless.</p>
</div>
</div>
</div>
</div>
<footer><divclass="rst-footer-buttons" role="navigation" aria-label="Footer">
<ahref="Introduction.html" class="btn btn-neutral float-left" title="Introducing Control Flow" accesskey="p" rel="prev"><spanclass="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<ahref="ForLoops.html" class="btn btn-neutral float-right" title="For-Loops and While-Loops" accesskey="n" rel="next">Next <spanclass="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
<divrole="contentinfo">
<p>© Copyright 2021, Ryan Soklaski.</p>
</div>
Built with <ahref="https://www.sphinx-doc.org/">Sphinx</a> using a
<ahref="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <ahref="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function(){
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>