-
-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathcompound_stmts.html
1949 lines (1891 loc) · 209 KB
/
compound_stmts.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
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-TW" data-content_root="../">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>8. 複合陳述式 — Python 3.13.2 說明文件</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
<script src="../_static/documentation_options.js?v=9a295789"></script>
<script src="../_static/doctools.js?v=9bcbadda"></script>
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="../_static/translations.js?v=cbf116e0"></script>
<script src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.13.2 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="版權" href="../copyright.html" />
<link rel="next" title="9. 最高層級元件" href="toplevel_components.html" />
<link rel="prev" title="7. 簡單陳述式" href="simple_stmts.html" />
<link rel="canonical" href="https://docs.python.org/3/reference/compound_stmts.html" />
<style>
@media only screen {
table.full-width-table {
width: 100%;
}
}
</style>
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/menu.js"></script>
<script type="text/javascript" src="../_static/search-focus.js"></script>
<script type="text/javascript" src="../_static/themetoggle.js"></script>
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
<meta name="readthedocs-addons-api-version" content="1">
</head>
<body>
<div class="mobile-nav">
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
<nav class="nav-content" role="navigation">
<label for="menuToggler" class="toggler__label">
<span></span>
</label>
<span class="nav-items-wrapper">
<a href="https://www.python.org/" class="nav-logo">
<img src="../_static/py.svg" alt="Python logo"/>
</a>
<span class="version_switcher_placeholder"></span>
<form role="search" class="search" action="../search.html" method="get">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
<path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
</svg>
<input placeholder="快速搜尋" aria-label="快速搜尋" type="search" name="q" />
<input type="submit" value="前往"/>
</form>
</span>
</nav>
<div class="menu-wrapper">
<nav class="menu" role="navigation" aria-label="main navigation">
<div class="language_switcher_placeholder"></div>
<label class="theme-selector-label">
Theme
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>Auto</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</label>
<div>
<h3><a href="../contents.html">目錄</a></h3>
<ul>
<li><a class="reference internal" href="#">8. 複合陳述式</a><ul>
<li><a class="reference internal" href="#the-if-statement">8.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> 陳述式</a></li>
<li><a class="reference internal" href="#the-while-statement">8.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> 陳述式</a></li>
<li><a class="reference internal" href="#the-for-statement">8.3. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> 陳述式</a></li>
<li><a class="reference internal" href="#the-try-statement">8.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> 陳述式</a><ul>
<li><a class="reference internal" href="#except-clause">8.4.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> 子句</a></li>
<li><a class="reference internal" href="#except-star">8.4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> 子句</a></li>
<li><a class="reference internal" href="#else-clause">8.4.3. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> 子句</a></li>
<li><a class="reference internal" href="#finally-clause">8.4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> 子句</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-with-statement">8.5. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 陳述式</a></li>
<li><a class="reference internal" href="#the-match-statement">8.6. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> 陳述式</a><ul>
<li><a class="reference internal" href="#overview">8.6.1. Overview</a></li>
<li><a class="reference internal" href="#guards">8.6.2. Guards</a></li>
<li><a class="reference internal" href="#irrefutable-case-blocks">8.6.3. Irrefutable Case Blocks</a></li>
<li><a class="reference internal" href="#patterns">8.6.4. Patterns</a><ul>
<li><a class="reference internal" href="#or-patterns">8.6.4.1. OR Patterns</a></li>
<li><a class="reference internal" href="#as-patterns">8.6.4.2. AS Patterns</a></li>
<li><a class="reference internal" href="#literal-patterns">8.6.4.3. Literal Patterns</a></li>
<li><a class="reference internal" href="#capture-patterns">8.6.4.4. Capture Patterns</a></li>
<li><a class="reference internal" href="#wildcard-patterns">8.6.4.5. Wildcard Patterns</a></li>
<li><a class="reference internal" href="#value-patterns">8.6.4.6. Value Patterns</a></li>
<li><a class="reference internal" href="#group-patterns">8.6.4.7. Group Patterns</a></li>
<li><a class="reference internal" href="#sequence-patterns">8.6.4.8. Sequence Patterns</a></li>
<li><a class="reference internal" href="#mapping-patterns">8.6.4.9. Mapping Patterns</a></li>
<li><a class="reference internal" href="#class-patterns">8.6.4.10. Class Patterns</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#function-definitions">8.7. 函式定義</a></li>
<li><a class="reference internal" href="#class-definitions">8.8. 類別定義</a></li>
<li><a class="reference internal" href="#coroutines">8.9. 協程</a><ul>
<li><a class="reference internal" href="#coroutine-function-definition">8.9.1. 協程函式定義</a></li>
<li><a class="reference internal" href="#the-async-for-statement">8.9.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code> 陳述式</a></li>
<li><a class="reference internal" href="#the-async-with-statement">8.9.3. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code> 陳述式</a></li>
</ul>
</li>
<li><a class="reference internal" href="#type-parameter-lists">8.10. Type parameter lists</a><ul>
<li><a class="reference internal" href="#generic-functions">8.10.1. Generic functions</a></li>
<li><a class="reference internal" href="#generic-classes">8.10.2. Generic classes</a></li>
<li><a class="reference internal" href="#generic-type-aliases">8.10.3. Generic type aliases</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div>
<h4>上個主題</h4>
<p class="topless"><a href="simple_stmts.html"
title="上一章"><span class="section-number">7. </span>簡單陳述式</a></p>
</div>
<div>
<h4>下個主題</h4>
<p class="topless"><a href="toplevel_components.html"
title="下一章"><span class="section-number">9. </span>最高層級元件</a></p>
</div>
<div role="note" aria-label="source link">
<h3>此頁面</h3>
<ul class="this-page-menu">
<li><a href="../bugs.html">回報錯誤</a></li>
<li>
<a href="https://github.com/python/cpython/blob/main/Doc/reference/compound_stmts.rst"
rel="nofollow">顯示原始碼
</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
<div class="related" role="navigation" aria-label="Related">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="總索引"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="toplevel_components.html" title="9. 最高層級元件"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="simple_stmts.html" title="7. 簡單陳述式"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li class="switchers">
<div class="language_switcher_placeholder"></div>
<div class="version_switcher_placeholder"></div>
</li>
<li>
</li>
<li id="cpython-language-and-version">
<a href="../index.html">3.13.2 Documentation</a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python 語言參考手冊</a> »</li>
<li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>複合陳述式</a></li>
<li class="right">
<div class="inline-search" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="快速搜尋" aria-label="快速搜尋" type="search" name="q" id="search-box" />
<input type="submit" value="前往" />
</form>
</div>
|
</li>
<li class="right">
<label class="theme-selector-label">
Theme
<select class="theme-selector" oninput="activateTheme(this.value)">
<option value="auto" selected>Auto</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</label> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<section id="compound-statements">
<span id="compound"></span><h1><span class="section-number">8. </span>複合陳述式<a class="headerlink" href="#compound-statements" title="連結到這個標頭">¶</a></h1>
<p id="index-0">Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way. In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.</p>
<p>The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> and <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements implement
traditional control flow constructs. <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> specifies exception
handlers and/or cleanup code for a group of statements, while the
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows the execution of initialization and
finalization code around a block of code. Function and class definitions are
also syntactically compound statements.</p>
<p id="index-1">A compound statement consists of one or more 'clauses.' A clause consists of a
header and a 'suite.' The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon. A suite is a group of statements
controlled by a clause. A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header's colon, or it
can be one or more indented statements on subsequent lines. Only the latter
form of a suite can contain nested compound statements; the following is illegal,
mostly because it wouldn't be clear to which <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause a following
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause would belong:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">test1</span><span class="p">:</span> <span class="k">if</span> <span class="n">test2</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> calls are
executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="n">y</span> <span class="o"><</span> <span class="n">z</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">y</span><span class="p">);</span> <span class="nb">print</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>
</pre></div>
</div>
<p>Summarizing:</p>
<pre>
<strong id="grammar-token-python-grammar-compound_stmt">compound_stmt</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-if_stmt"><code class="xref docutils literal notranslate"><span class="pre">if_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-while_stmt"><code class="xref docutils literal notranslate"><span class="pre">while_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-for_stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-try_stmt"><code class="xref docutils literal notranslate"><span class="pre">try_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-with_stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-match_stmt"><code class="xref docutils literal notranslate"><span class="pre">match_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-async_with_stmt"><code class="xref docutils literal notranslate"><span class="pre">async_with_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-async_for_stmt"><code class="xref docutils literal notranslate"><span class="pre">async_for_stmt</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-async_funcdef"><code class="xref docutils literal notranslate"><span class="pre">async_funcdef</span></code></a>
<strong id="grammar-token-python-grammar-suite">suite</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-stmt_list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>+ DEDENT
<strong id="grammar-token-python-grammar-statement">statement</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-stmt_list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | <a class="reference internal" href="#grammar-token-python-grammar-compound_stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a>
<strong id="grammar-token-python-grammar-stmt_list">stmt_list</strong> ::= <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a> (";" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a>)* [";"]
</pre>
<p id="index-2">Note that statements always end in a <code class="docutils literal notranslate"><span class="pre">NEWLINE</span></code> possibly followed by a
<code class="docutils literal notranslate"><span class="pre">DEDENT</span></code>. Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
'dangling <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>' problem is solved in Python by requiring nested
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements to be indented).</p>
<p>The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.</p>
<section id="the-if-statement">
<span id="else"></span><span id="elif"></span><span id="if"></span><h2><span class="section-number">8.1. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> 陳述式<a class="headerlink" href="#the-if-statement" title="連結到這個標頭">¶</a></h2>
<p id="index-3">The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is used for conditional execution:</p>
<pre>
<strong id="grammar-token-python-grammar-if_stmt">if_stmt</strong> ::= "if" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
("elif" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)*
["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section <a class="reference internal" href="expressions.html#booleans"><span class="std std-ref">Boolean operations</span></a> for the definition of
true and false); then that suite is executed (and no other part of the
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is executed or evaluated). If all expressions are
false, the suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed.</p>
</section>
<section id="the-while-statement">
<span id="while"></span><h2><span class="section-number">8.2. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code> 陳述式<a class="headerlink" href="#the-while-statement" title="連結到這個標頭">¶</a></h2>
<p id="index-4">The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement is used for repeated execution as long as an
expression is true:</p>
<pre>
<strong id="grammar-token-python-grammar-while_stmt">while_stmt</strong> ::= "while" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-assignment_expression"><code class="xref docutils literal notranslate"><span class="pre">assignment_expression</span></code></a> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause, if present, is executed and the loop
terminates.</p>
<p id="index-5">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause's suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.</p>
</section>
<section id="the-for-statement">
<span id="for"></span><h2><span class="section-number">8.3. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> 陳述式<a class="headerlink" href="#the-for-statement" title="連結到這個標頭">¶</a></h2>
<p id="index-6">The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:</p>
<pre>
<strong id="grammar-token-python-grammar-for_stmt">for_stmt</strong> ::= "for" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> "in" <code class="xref docutils literal notranslate"><span class="pre">starred_list</span></code> ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>The <code class="docutils literal notranslate"><span class="pre">starred_list</span></code> expression is evaluated once; it should yield an
<a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> object. An <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> is created for that iterable.
The first item provided
by the iterator is then assigned to the target list using the standard
rules for assignments (see <a class="reference internal" href="simple_stmts.html#assignment"><span class="std std-ref">Assignment statements</span></a>), and the suite is executed. This
repeats for each item provided by the iterator. When the iterator is exhausted,
the suite in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause,
if present, is executed, and the loop terminates.</p>
<p id="index-7">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause's suite. A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause if there is no next
item.</p>
<p>The for-loop makes assignments to the variables in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1"># this will not affect the for-loop</span>
<span class="c1"># because i will be overwritten with the next</span>
<span class="c1"># index in the range</span>
</pre></div>
</div>
<p id="index-8">Names in the target list are not deleted when the loop is finished, but if the
sequence is empty, they will not have been assigned to at all by the loop. Hint:
the built-in type <a class="reference internal" href="../library/stdtypes.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> represents immutable arithmetic sequences of integers.
For instance, iterating <code class="docutils literal notranslate"><span class="pre">range(3)</span></code> successively yields 0, 1, and then 2.</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.11 版的變更: </span>Starred elements are now allowed in the expression list.</p>
</div>
</section>
<section id="the-try-statement">
<span id="try"></span><h2><span class="section-number">8.4. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> 陳述式<a class="headerlink" href="#the-try-statement" title="連結到這個標頭">¶</a></h2>
<p id="index-9">The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement specifies exception handlers and/or cleanup code
for a group of statements:</p>
<pre>
<strong id="grammar-token-python-grammar-try_stmt">try_stmt</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-try1_stmt"><code class="xref docutils literal notranslate"><span class="pre">try1_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-try2_stmt"><code class="xref docutils literal notranslate"><span class="pre">try2_stmt</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-try3_stmt"><code class="xref docutils literal notranslate"><span class="pre">try3_stmt</span></code></a>
<strong id="grammar-token-python-grammar-try1_stmt">try1_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
("except" [<a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ["as" <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
["finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
<strong id="grammar-token-python-grammar-try2_stmt">try2_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
("except" "*" <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ["as" <a class="reference internal" href="lexical_analysis.html#grammar-token-python-grammar-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
["else" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
["finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
<strong id="grammar-token-python-grammar-try3_stmt">try3_stmt</strong> ::= "try" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
"finally" ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">例外</span></a>,
and information on using the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement to generate exceptions
may be found in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">raise 陳述式</span></a>.</p>
<section id="except-clause">
<span id="except"></span><h3><span class="section-number">8.4.1. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> 子句<a class="headerlink" href="#except-clause" title="連結到這個標頭">¶</a></h3>
<p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause(s) specify one or more exception handlers. When no
exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, no exception handler is executed.
When an exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> suite, a search for an exception
handler is started. This search inspects the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clauses in turn
until one is found that matches the exception.
An expression-less <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause, if present, must be last;
it matches any exception.</p>
<p>For an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause with an expression, the
expression must evaluate to an exception type or a tuple of exception types.
The raised exception matches an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause whose expression evaluates
to the class or a <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">non-virtual base class</span></a> of the exception object,
or to a tuple that contains such a class.</p>
<p>If no <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause matches the exception,
the search for an exception handler
continues in the surrounding code and on the invocation stack. <a class="footnote-reference brackets" href="#id20" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p>
<p>If the evaluation of an expression
in the header of an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause raises an exception,
the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement raised the exception).</p>
<p id="index-10">When a matching <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause is found,
the exception is assigned to the target
specified after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> keyword in that <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause,
if present, and the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause's suite is executed.
All <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clauses must have an executable block.
When the end of this block is reached, execution continues
normally after the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement.
(This means that if two nested handlers exist for the same exception,
and the exception occurs in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> clause of the inner handler,
the outer handler will not handle the exception.)</p>
<p>When an exception has been assigned using <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">target</span></code>, it is cleared at the
end of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause. This is as if</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
<span class="n">foo</span>
</pre></div>
</div>
<p>was translated to</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">except</span> <span class="n">E</span> <span class="k">as</span> <span class="n">N</span><span class="p">:</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">foo</span>
<span class="k">finally</span><span class="p">:</span>
<span class="k">del</span> <span class="n">N</span>
</pre></div>
</div>
<p>This means the exception must be assigned to a different name to be able to
refer to it after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause.
Exceptions are cleared because with the
traceback attached to them, they form a reference cycle with the stack frame,
keeping all locals in that frame alive until the next garbage collection occurs.</p>
<p id="index-11">Before an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause's suite is executed,
the exception is stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, where it can be accessed
from within the body of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> clause by calling
<a class="reference internal" href="../library/sys.html#sys.exception" title="sys.exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exception()</span></code></a>. When leaving an exception handler, the exception
stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module is reset to its previous value:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">())</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span>
<span class="gp">... </span><span class="k">except</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">()))</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">ValueError</span>
<span class="gp">... </span> <span class="k">except</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">()))</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">()))</span>
<span class="gp">...</span>
<span class="go">TypeError()</span>
<span class="go">ValueError()</span>
<span class="go">TypeError()</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exception</span><span class="p">())</span>
<span class="go">None</span>
</pre></div>
</div>
</section>
<section id="except-star">
<span id="index-12"></span><span id="id2"></span><h3><span class="section-number">8.4.2. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> 子句<a class="headerlink" href="#except-star" title="連結到這個標頭">¶</a></h3>
<p>The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause(s) are used for handling
<a class="reference internal" href="../library/exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a>s. The exception type for matching is interpreted as in
the case of <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>, but in the case of exception groups we can have
partial matches when the type matches some of the exceptions in the group.
This means that multiple <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses can execute,
each handling part of the exception group.
Each clause executes at most once and handles an exception group
of all matching exceptions. Each exception in the group is handled by at most
one <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause, the first that matches it.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s2">"eg"</span><span class="p">,</span>
<span class="gp">... </span> <span class="p">[</span><span class="ne">ValueError</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="ne">TypeError</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">4</span><span class="p">)])</span>
<span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">TypeError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1"> with nested </span><span class="si">{</span><span class="n">e</span><span class="o">.</span><span class="n">exceptions</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1"> with nested </span><span class="si">{</span><span class="n">e</span><span class="o">.</span><span class="n">exceptions</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">caught <class 'ExceptionGroup'> with nested (TypeError(2),)</span>
<span class="go">caught <class 'ExceptionGroup'> with nested (OSError(3), OSError(4))</span>
<span class="go"> + Exception Group Traceback (most recent call last):</span>
<span class="go"> | File "<stdin>", line 2, in <module></span>
<span class="go"> | ExceptionGroup: eg</span>
<span class="go"> +-+---------------- 1 ----------------</span>
<span class="go"> | ValueError: 1</span>
<span class="go"> +------------------------------------</span>
</pre></div>
</div>
<p>Any remaining exceptions that were not handled by any <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code>
clause are re-raised at the end, along with all exceptions that were
raised from within the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses. If this list contains
more than one exception to reraise, they are combined into an exception
group.</p>
<p>If the raised exception is not an exception group and its type matches
one of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clauses, it is caught and wrapped by an
exception group with an empty message string.</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">BlockingIOError</span>
<span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">BlockingIOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">e</span><span class="p">))</span>
<span class="gp">...</span>
<span class="go">ExceptionGroup('', (BlockingIOError()))</span>
</pre></div>
</div>
<p>An <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause must have a matching expression; it cannot be <code class="docutils literal notranslate"><span class="pre">except*:</span></code>.
Furthermore, this expression cannot contain exception group types, because that would
have ambiguous semantics.</p>
<p>It is not possible to mix <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code>
in the same <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>.
<a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> and <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
cannot appear in an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except*</span></code> clause.</p>
</section>
<section id="else-clause">
<span id="except-else"></span><span id="index-13"></span><h3><span class="section-number">8.4.3. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> 子句<a class="headerlink" href="#else-clause" title="連結到這個標頭">¶</a></h3>
<p>The optional <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is executed if the control flow leaves the
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>,
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>, or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement was executed. Exceptions in
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause are not handled by the preceding <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
clauses.</p>
</section>
<section id="finally-clause">
<span id="finally"></span><span id="index-14"></span><h3><span class="section-number">8.4.4. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> 子句<a class="headerlink" href="#finally-clause" title="連結到這個標頭">¶</a></h3>
<p>If <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> is present, it specifies a 'cleanup' handler. The
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause is executed, including any <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clauses. If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause
is executed. If there is a saved exception it is re-raised at the end of the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause. If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause raises another
exception, the saved exception is set as the context of the new exception.
If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>
or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement, the saved exception is discarded:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="mi">42</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The exception information is not available to the program during execution of
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause.</p>
<p id="index-15">When a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is
executed in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite of a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>...<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
statement, the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause is also executed 'on the way out.'</p>
<p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
statement executed. Since the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause always executes, a
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement executed in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will
always be the last one executed:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">'try'</span>
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">return</span> <span class="s1">'finally'</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">foo</span><span class="p">()</span>
<span class="go">'finally'</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.8 版的變更: </span>Prior to Python 3.8, a <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement was illegal in the
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause due to a problem with the implementation.</p>
</div>
</section>
</section>
<section id="the-with-statement">
<span id="as"></span><span id="with"></span><h2><span class="section-number">8.5. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> 陳述式<a class="headerlink" href="#the-with-statement" title="連結到這個標頭">¶</a></h2>
<p id="index-16">The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is used to wrap the execution of a block with
methods defined by a context manager (see section <a class="reference internal" href="datamodel.html#context-managers"><span class="std std-ref">With 陳述式的情境管理器</span></a>).
This allows common <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>...<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>...<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
usage patterns to be encapsulated for convenient reuse.</p>
<pre>
<strong id="grammar-token-python-grammar-with_stmt">with_stmt</strong> ::= "with" ( "(" <a class="reference internal" href="#grammar-token-python-grammar-with_stmt_contents"><code class="xref docutils literal notranslate"><span class="pre">with_stmt_contents</span></code></a> ","? ")" | <a class="reference internal" href="#grammar-token-python-grammar-with_stmt_contents"><code class="xref docutils literal notranslate"><span class="pre">with_stmt_contents</span></code></a> ) ":" <a class="reference internal" href="#grammar-token-python-grammar-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-python-grammar-with_stmt_contents">with_stmt_contents</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-with_item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a> ("," <a class="reference internal" href="#grammar-token-python-grammar-with_item"><code class="xref docutils literal notranslate"><span class="pre">with_item</span></code></a>)*
<strong id="grammar-token-python-grammar-with_item">with_item</strong> ::= <a class="reference internal" href="expressions.html#grammar-token-python-grammar-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ["as" <a class="reference internal" href="simple_stmts.html#grammar-token-python-grammar-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>]
</pre>
<p>The execution of the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement with one "item" proceeds as follows:</p>
<ol class="arabic">
<li><p>The context expression (the expression given in the
<a class="reference internal" href="#grammar-token-python-grammar-with_item"><code class="xref std std-token docutils literal notranslate"><span class="pre">with_item</span></code></a>) is evaluated to obtain a context manager.</p></li>
<li><p>The context manager's <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is loaded for later use.</p></li>
<li><p>The context manager's <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is loaded for later use.</p></li>
<li><p>The context manager's <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is invoked.</p></li>
<li><p>If a target was included in the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the return value
from <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is assigned to it.</p>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>
method returns without an error, then <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> will always be
called. Thus, if an error occurs during the assignment to the target list,
it will be treated the same as an error occurring within the suite would
be. See step 7 below.</p>
</div>
</li>
<li><p>The suite is executed.</p></li>
<li><p>The context manager's <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are passed as
arguments to <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>. Otherwise, three <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> arguments are
supplied.</p>
<p>If the suite was exited due to an exception, and the return value from the
<a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method was false, the exception is reraised. If the return
value was true, the exception is suppressed, and execution continues with the
statement following the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>If the suite was exited for any reason other than an exception, the return
value from <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is ignored, and execution proceeds at the normal
location for the kind of exit that was taken.</p>
</li>
</ol>
<p>以下程式碼:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">EXPRESSION</span> <span class="k">as</span> <span class="n">TARGET</span><span class="p">:</span>
<span class="n">SUITE</span>
</pre></div>
</div>
<p>在語義上等同於:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">manager</span> <span class="o">=</span> <span class="p">(</span><span class="n">EXPRESSION</span><span class="p">)</span>
<span class="n">enter</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__enter__</span>
<span class="n">exit</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span><span class="o">.</span><span class="fm">__exit__</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">enter</span><span class="p">(</span><span class="n">manager</span><span class="p">)</span>
<span class="n">hit_except</span> <span class="o">=</span> <span class="kc">False</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">TARGET</span> <span class="o">=</span> <span class="n">value</span>
<span class="n">SUITE</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">hit_except</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="o">*</span><span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()):</span>
<span class="k">raise</span>
<span class="k">finally</span><span class="p">:</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">hit_except</span><span class="p">:</span>
<span class="n">exit</span><span class="p">(</span><span class="n">manager</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>With more than one item, the context managers are processed as if multiple
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements were nested:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
<span class="n">SUITE</span>
</pre></div>
</div>
<p>在語義上等同於:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span>
<span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
<span class="n">SUITE</span>
</pre></div>
</div>
<p>You can also write multi-item context managers in multiple lines if
the items are surrounded by parentheses. For example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="p">(</span>
<span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span>
<span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">,</span>
<span class="p">):</span>
<span class="n">SUITE</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版的變更: </span>Support for multiple context expressions.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.10 版的變更: </span>Support for using grouping parentheses to break the statement in multiple lines.</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">也參考</p>
<dl class="simple">
<dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The "with" statement</dt><dd><p>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</p>
</dd>
</dl>
</div>
</section>
<section id="the-match-statement">
<span id="match"></span><h2><span class="section-number">8.6. </span><code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> 陳述式<a class="headerlink" href="#the-match-statement" title="連結到這個標頭">¶</a></h2>
<div class="versionadded" id="index-18">
<p><span class="versionmodified added">在 3.10 版被加入.</span></p>
</div>
<p>The match statement is used for pattern matching. Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-match_stmt">match_stmt</strong> ::= 'match' <a class="reference internal" href="#grammar-token-python-grammar-subject_expr"><code class="xref docutils literal notranslate"><span class="pre">subject_expr</span></code></a> ":" NEWLINE INDENT <a class="reference internal" href="#grammar-token-python-grammar-case_block"><code class="xref docutils literal notranslate"><span class="pre">case_block</span></code></a>+ DEDENT
<strong id="grammar-token-python-grammar-subject_expr">subject_expr</strong> ::= <code class="xref docutils literal notranslate"><span class="pre">star_named_expression</span></code> "," <code class="xref docutils literal notranslate"><span class="pre">star_named_expressions</span></code>?
| <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></code>
<strong id="grammar-token-python-grammar-case_block">case_block</strong> ::= 'case' <a class="reference internal" href="#grammar-token-python-grammar-patterns"><code class="xref docutils literal notranslate"><span class="pre">patterns</span></code></a> [<a class="reference internal" href="#grammar-token-python-grammar-guard"><code class="xref docutils literal notranslate"><span class="pre">guard</span></code></a>] ":" <code class="xref docutils literal notranslate"><span class="pre">block</span></code>
</pre>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>This section uses single quotes to denote
<a class="reference internal" href="lexical_analysis.html#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p>
</div>
<p>Pattern matching takes a pattern as input (following <code class="docutils literal notranslate"><span class="pre">case</span></code>) and a subject
value (following <code class="docutils literal notranslate"><span class="pre">match</span></code>). The pattern (which may contain subpatterns) is
matched against the subject value. The outcomes are:</p>
<ul class="simple">
<li><p>A match success or failure (also termed a pattern success or failure).</p></li>
<li><p>Possible binding of matched values to a name. The prerequisites for this are
further discussed below.</p></li>
</ul>
<p>The <code class="docutils literal notranslate"><span class="pre">match</span></code> and <code class="docutils literal notranslate"><span class="pre">case</span></code> keywords are <a class="reference internal" href="lexical_analysis.html#soft-keywords"><span class="std std-ref">soft keywords</span></a>.</p>
<div class="admonition seealso">
<p class="admonition-title">也參考</p>
<ul class="simple">
<li><p><span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> -- Structural Pattern Matching: Specification</p></li>
<li><p><span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0636/"><strong>PEP 636</strong></a> -- Structural Pattern Matching: Tutorial</p></li>
</ul>
</div>
<section id="overview">
<h3><span class="section-number">8.6.1. </span>Overview<a class="headerlink" href="#overview" title="連結到這個標頭">¶</a></h3>
<p>Here's an overview of the logical flow of a match statement:</p>
<ol class="arabic">
<li><p>The subject expression <code class="docutils literal notranslate"><span class="pre">subject_expr</span></code> is evaluated and a resulting subject
value obtained. If the subject expression contains a comma, a tuple is
constructed using <a class="reference internal" href="../library/stdtypes.html#typesseq-tuple"><span class="std std-ref">the standard rules</span></a>.</p></li>
<li><p>Each pattern in a <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is attempted to match with the subject value. The
specific rules for success or failure are described below. The match attempt can also
bind some or all of the standalone names within the pattern. The precise
pattern binding rules vary per pattern type and are
specified below. <strong>Name bindings made during a successful pattern match
outlive the executed block and can be used after the match statement</strong>.</p>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>During failed pattern matches, some subpatterns may succeed. Do not
rely on bindings being made for a failed match. Conversely, do not
rely on variables remaining unchanged after a failed match. The exact
behavior is dependent on implementation and may vary. This is an
intentional decision made to allow different implementations to add
optimizations.</p>
</div>
</li>
<li><p>If the pattern succeeds, the corresponding guard (if present) is evaluated. In
this case all name bindings are guaranteed to have happened.</p>
<ul class="simple">
<li><p>If the guard evaluates as true or is missing, the <code class="docutils literal notranslate"><span class="pre">block</span></code> inside
<code class="docutils literal notranslate"><span class="pre">case_block</span></code> is executed.</p></li>
<li><p>Otherwise, the next <code class="docutils literal notranslate"><span class="pre">case_block</span></code> is attempted as described above.</p></li>
<li><p>If there are no further case blocks, the match statement is completed.</p></li>
</ul>
</li>
</ol>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>Users should generally never rely on a pattern being evaluated. Depending on
implementation, the interpreter may cache values or use other optimizations
which skip repeated evaluations.</p>
</div>
<p>A sample match statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">flag</span> <span class="o">=</span> <span class="kc">False</span>
<span class="gp">>>> </span><span class="k">match</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">):</span>
<span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">300</span><span class="p">):</span> <span class="c1"># Mismatch: 200 != 300</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 1'</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">200</span><span class="p">)</span> <span class="k">if</span> <span class="n">flag</span><span class="p">:</span> <span class="c1"># Successful match, but guard fails</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 2'</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">case</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="c1"># Matches and binds y to 200</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Case 3, y: </span><span class="si">{</span><span class="n">y</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
<span class="gp">... </span> <span class="k">case</span><span class="w"> </span><span class="k">_</span><span class="p">:</span> <span class="c1"># Pattern not attempted</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Case 4, I match anything!'</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Case 3, y: 200</span>
</pre></div>
</div>
<p>In this case, <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">flag</span></code> is a guard. Read more about that in the next section.</p>
</section>
<section id="guards">
<h3><span class="section-number">8.6.2. </span>Guards<a class="headerlink" href="#guards" title="連結到這個標頭">¶</a></h3>
<pre id="index-21">
<strong id="grammar-token-python-grammar-guard">guard</strong> ::= "if" <code class="xref docutils literal notranslate"><span class="pre">named_expression</span></code>
</pre>
<p>A <code class="docutils literal notranslate"><span class="pre">guard</span></code> (which is part of the <code class="docutils literal notranslate"><span class="pre">case</span></code>) must succeed for code inside
the <code class="docutils literal notranslate"><span class="pre">case</span></code> block to execute. It takes the form: <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> followed by an
expression.</p>
<p>The logical flow of a <code class="docutils literal notranslate"><span class="pre">case</span></code> block with a <code class="docutils literal notranslate"><span class="pre">guard</span></code> follows:</p>
<ol class="arabic simple">
<li><p>Check that the pattern in the <code class="docutils literal notranslate"><span class="pre">case</span></code> block succeeded. If the pattern
failed, the <code class="docutils literal notranslate"><span class="pre">guard</span></code> is not evaluated and the next <code class="docutils literal notranslate"><span class="pre">case</span></code> block is
checked.</p></li>
<li><p>If the pattern succeeded, evaluate the <code class="docutils literal notranslate"><span class="pre">guard</span></code>.</p>
<ul class="simple">
<li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as true, the case block is
selected.</p></li>
<li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> condition evaluates as false, the case block is not
selected.</p></li>
<li><p>If the <code class="docutils literal notranslate"><span class="pre">guard</span></code> raises an exception during evaluation, the exception
bubbles up.</p></li>
</ul>
</li>
</ol>
<p>Guards are allowed to have side effects as they are expressions. Guard
evaluation must proceed from the first to the last case block, one at a time,
skipping case blocks whose pattern(s) don't all succeed. (I.e.,
guard evaluation must happen in order.) Guard evaluation must stop once a case
block is selected.</p>
</section>
<section id="irrefutable-case-blocks">
<span id="irrefutable-case"></span><h3><span class="section-number">8.6.3. </span>Irrefutable Case Blocks<a class="headerlink" href="#irrefutable-case-blocks" title="連結到這個標頭">¶</a></h3>
<p id="index-22">An irrefutable case block is a match-all case block. A match statement may have
at most one irrefutable case block, and it must be last.</p>
<p>A case block is considered irrefutable if it has no guard and its pattern is
irrefutable. A pattern is considered irrefutable if we can prove from its
syntax alone that it will always succeed. Only the following patterns are
irrefutable:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#as-patterns"><span class="std std-ref">AS Patterns</span></a> whose left-hand side is irrefutable</p></li>
<li><p><a class="reference internal" href="#or-patterns"><span class="std std-ref">OR Patterns</span></a> containing at least one irrefutable pattern</p></li>
<li><p><a class="reference internal" href="#capture-patterns"><span class="std std-ref">Capture Patterns</span></a></p></li>
<li><p><a class="reference internal" href="#wildcard-patterns"><span class="std std-ref">Wildcard Patterns</span></a></p></li>
<li><p>parenthesized irrefutable patterns</p></li>
</ul>
</section>
<section id="patterns">
<h3><span class="section-number">8.6.4. </span>Patterns<a class="headerlink" href="#patterns" title="連結到這個標頭">¶</a></h3>
<div class="admonition note" id="index-23">
<p class="admonition-title">備註</p>
<p>This section uses grammar notations beyond standard EBNF:</p>
<ul class="simple">
<li><p>the notation <code class="docutils literal notranslate"><span class="pre">SEP.RULE+</span></code> is shorthand for <code class="docutils literal notranslate"><span class="pre">RULE</span> <span class="pre">(SEP</span> <span class="pre">RULE)*</span></code></p></li>
<li><p>the notation <code class="docutils literal notranslate"><span class="pre">!RULE</span></code> is shorthand for a negative lookahead assertion</p></li>
</ul>
</div>
<p>The top-level syntax for <code class="docutils literal notranslate"><span class="pre">patterns</span></code> is:</p>
<pre>
<strong id="grammar-token-python-grammar-patterns">patterns</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-open_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">open_sequence_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a>
<strong id="grammar-token-python-grammar-pattern">pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-as_pattern"><code class="xref docutils literal notranslate"><span class="pre">as_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-or_pattern"><code class="xref docutils literal notranslate"><span class="pre">or_pattern</span></code></a>
<strong id="grammar-token-python-grammar-closed_pattern">closed_pattern</strong> ::= | <a class="reference internal" href="#grammar-token-python-grammar-literal_pattern"><code class="xref docutils literal notranslate"><span class="pre">literal_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-value_pattern"><code class="xref docutils literal notranslate"><span class="pre">value_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-group_pattern"><code class="xref docutils literal notranslate"><span class="pre">group_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">sequence_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-mapping_pattern"><code class="xref docutils literal notranslate"><span class="pre">mapping_pattern</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-class_pattern"><code class="xref docutils literal notranslate"><span class="pre">class_pattern</span></code></a>
</pre>
<p>The descriptions below will include a description "in simple terms" of what a pattern
does for illustration purposes (credits to Raymond Hettinger for a document that
inspired most of the descriptions). Note that these descriptions are purely for
illustration purposes and <strong>may not</strong> reflect
the underlying implementation. Furthermore, they do not cover all valid forms.</p>
<section id="or-patterns">
<span id="id3"></span><h4><span class="section-number">8.6.4.1. </span>OR Patterns<a class="headerlink" href="#or-patterns" title="連結到這個標頭">¶</a></h4>
<p>An OR pattern is two or more patterns separated by vertical
bars <code class="docutils literal notranslate"><span class="pre">|</span></code>. Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-or_pattern">or_pattern</strong> ::= "|".<a class="reference internal" href="#grammar-token-python-grammar-closed_pattern"><code class="xref docutils literal notranslate"><span class="pre">closed_pattern</span></code></a>+
</pre>
<p>Only the final subpattern may be <a class="reference internal" href="#irrefutable-case"><span class="std std-ref">irrefutable</span></a>, and each
subpattern must bind the same set of names to avoid ambiguity.</p>
<p>An OR pattern matches each of its subpatterns in turn to the subject value,
until one succeeds. The OR pattern is then considered successful. Otherwise,
if none of the subpatterns succeed, the OR pattern fails.</p>
<p>In simple terms, <code class="docutils literal notranslate"><span class="pre">P1</span> <span class="pre">|</span> <span class="pre">P2</span> <span class="pre">|</span> <span class="pre">...</span></code> will try to match <code class="docutils literal notranslate"><span class="pre">P1</span></code>, if it fails it will try to
match <code class="docutils literal notranslate"><span class="pre">P2</span></code>, succeeding immediately if any succeeds, failing otherwise.</p>
</section>
<section id="as-patterns">
<span id="id4"></span><h4><span class="section-number">8.6.4.2. </span>AS Patterns<a class="headerlink" href="#as-patterns" title="連結到這個標頭">¶</a></h4>
<p>An AS pattern matches an OR pattern on the left of the <a class="reference internal" href="#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a>
keyword against a subject. Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-as_pattern">as_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-or_pattern"><code class="xref docutils literal notranslate"><span class="pre">or_pattern</span></code></a> "as" <a class="reference internal" href="#grammar-token-python-grammar-capture_pattern"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></a>
</pre>
<p>If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds
the subject to the name on the right of the as keyword and succeeds.
<code class="docutils literal notranslate"><span class="pre">capture_pattern</span></code> cannot be a <code class="docutils literal notranslate"><span class="pre">_</span></code>.</p>
<p>In simple terms <code class="docutils literal notranslate"><span class="pre">P</span> <span class="pre">as</span> <span class="pre">NAME</span></code> will match with <code class="docutils literal notranslate"><span class="pre">P</span></code>, and on success it will
set <code class="docutils literal notranslate"><span class="pre">NAME</span> <span class="pre">=</span> <span class="pre"><subject></span></code>.</p>
</section>
<section id="literal-patterns">
<span id="id5"></span><h4><span class="section-number">8.6.4.3. </span>Literal Patterns<a class="headerlink" href="#literal-patterns" title="連結到這個標頭">¶</a></h4>
<p>A literal pattern corresponds to most
<a class="reference internal" href="lexical_analysis.html#literals"><span class="std std-ref">literals</span></a> in Python. Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-literal_pattern">literal_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a>
| <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a> "+" NUMBER
| <a class="reference internal" href="#grammar-token-python-grammar-signed_number"><code class="xref docutils literal notranslate"><span class="pre">signed_number</span></code></a> "-" NUMBER
| <code class="xref docutils literal notranslate"><span class="pre">strings</span></code>
| "None"
| "True"
| "False"
<strong id="grammar-token-python-grammar-signed_number">signed_number</strong> ::= ["-"] NUMBER
</pre>
<p>The rule <code class="docutils literal notranslate"><span class="pre">strings</span></code> and the token <code class="docutils literal notranslate"><span class="pre">NUMBER</span></code> are defined in the
<a class="reference internal" href="grammar.html"><span class="doc">standard Python grammar</span></a>. Triple-quoted strings are
supported. Raw strings and byte strings are supported. <a class="reference internal" href="lexical_analysis.html#f-strings"><span class="std std-ref">f-string(f 字串)</span></a> are
not supported.</p>
<p>The forms <code class="docutils literal notranslate"><span class="pre">signed_number</span> <span class="pre">'+'</span> <span class="pre">NUMBER</span></code> and <code class="docutils literal notranslate"><span class="pre">signed_number</span> <span class="pre">'-'</span> <span class="pre">NUMBER</span></code> are
for expressing <a class="reference internal" href="lexical_analysis.html#imaginary"><span class="std std-ref">complex numbers</span></a>; they require a real number
on the left and an imaginary number on the right. E.g. <code class="docutils literal notranslate"><span class="pre">3</span> <span class="pre">+</span> <span class="pre">4j</span></code>.</p>
<p>In simple terms, <code class="docutils literal notranslate"><span class="pre">LITERAL</span></code> will succeed only if <code class="docutils literal notranslate"><span class="pre"><subject></span> <span class="pre">==</span> <span class="pre">LITERAL</span></code>. For
the singletons <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">True</span></code> and <code class="docutils literal notranslate"><span class="pre">False</span></code>, the <a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator is used.</p>
</section>
<section id="capture-patterns">
<span id="id6"></span><h4><span class="section-number">8.6.4.4. </span>Capture Patterns<a class="headerlink" href="#capture-patterns" title="連結到這個標頭">¶</a></h4>
<p>A capture pattern binds the subject value to a name.
Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-capture_pattern">capture_pattern</strong> ::= !'_' NAME
</pre>
<p>A single underscore <code class="docutils literal notranslate"><span class="pre">_</span></code> is not a capture pattern (this is what <code class="docutils literal notranslate"><span class="pre">!'_'</span></code>
expresses). It is instead treated as a
<a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref std std-token docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a>.</p>
<p>In a given pattern, a given name can only be bound once. E.g.
<code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">x,</span> <span class="pre">x:</span> <span class="pre">...</span></code> is invalid while <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">[x]</span> <span class="pre">|</span> <span class="pre">x:</span> <span class="pre">...</span></code> is allowed.</p>
<p>Capture patterns always succeed. The binding follows scoping rules
established by the assignment expression operator in <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>; the
name becomes a local variable in the closest containing function scope unless
there's an applicable <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> or <a class="reference internal" href="simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> statement.</p>
<p>In simple terms <code class="docutils literal notranslate"><span class="pre">NAME</span></code> will always succeed and it will set <code class="docutils literal notranslate"><span class="pre">NAME</span> <span class="pre">=</span> <span class="pre"><subject></span></code>.</p>
</section>
<section id="wildcard-patterns">
<span id="id7"></span><h4><span class="section-number">8.6.4.5. </span>Wildcard Patterns<a class="headerlink" href="#wildcard-patterns" title="連結到這個標頭">¶</a></h4>
<p>A wildcard pattern always succeeds (matches anything)
and binds no name. Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-wildcard_pattern">wildcard_pattern</strong> ::= '_'
</pre>
<p><code class="docutils literal notranslate"><span class="pre">_</span></code> is a <a class="reference internal" href="lexical_analysis.html#soft-keywords"><span class="std std-ref">soft keyword</span></a> within any pattern,
but only within patterns. It is an identifier, as usual, even within
<code class="docutils literal notranslate"><span class="pre">match</span></code> subject expressions, <code class="docutils literal notranslate"><span class="pre">guard</span></code>s, and <code class="docutils literal notranslate"><span class="pre">case</span></code> blocks.</p>
<p>In simple terms, <code class="docutils literal notranslate"><span class="pre">_</span></code> will always succeed.</p>
</section>
<section id="value-patterns">
<span id="id8"></span><h4><span class="section-number">8.6.4.6. </span>Value Patterns<a class="headerlink" href="#value-patterns" title="連結到這個標頭">¶</a></h4>
<p>A value pattern represents a named value in Python.
Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-value_pattern">value_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-attr"><code class="xref docutils literal notranslate"><span class="pre">attr</span></code></a>
<strong id="grammar-token-python-grammar-attr">attr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-name_or_attr"><code class="xref docutils literal notranslate"><span class="pre">name_or_attr</span></code></a> "." NAME
<strong id="grammar-token-python-grammar-name_or_attr">name_or_attr</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-attr"><code class="xref docutils literal notranslate"><span class="pre">attr</span></code></a> | NAME
</pre>
<p>The dotted name in the pattern is looked up using standard Python
<a class="reference internal" href="executionmodel.html#resolve-names"><span class="std std-ref">name resolution rules</span></a>. The pattern succeeds if the
value found compares equal to the subject value (using the <code class="docutils literal notranslate"><span class="pre">==</span></code> equality
operator).</p>
<p>In simple terms <code class="docutils literal notranslate"><span class="pre">NAME1.NAME2</span></code> will succeed only if <code class="docutils literal notranslate"><span class="pre"><subject></span> <span class="pre">==</span> <span class="pre">NAME1.NAME2</span></code></p>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>If the same value occurs multiple times in the same match statement, the
interpreter may cache the first value found and reuse it rather than repeat
the same lookup. This cache is strictly tied to a given execution of a
given match statement.</p>
</div>
</section>
<section id="group-patterns">
<span id="id9"></span><h4><span class="section-number">8.6.4.7. </span>Group Patterns<a class="headerlink" href="#group-patterns" title="連結到這個標頭">¶</a></h4>
<p>A group pattern allows users to add parentheses around patterns to
emphasize the intended grouping. Otherwise, it has no additional syntax.
Syntax:</p>
<pre>
<strong id="grammar-token-python-grammar-group_pattern">group_pattern</strong> ::= "(" <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a> ")"
</pre>
<p>In simple terms <code class="docutils literal notranslate"><span class="pre">(P)</span></code> has the same effect as <code class="docutils literal notranslate"><span class="pre">P</span></code>.</p>
</section>
<section id="sequence-patterns">
<span id="id10"></span><h4><span class="section-number">8.6.4.8. </span>Sequence Patterns<a class="headerlink" href="#sequence-patterns" title="連結到這個標頭">¶</a></h4>
<p>A sequence pattern contains several subpatterns to be matched against sequence elements.
The syntax is similar to the unpacking of a list or tuple.</p>
<pre>
<strong id="grammar-token-python-grammar-sequence_pattern">sequence_pattern</strong> ::= "[" [<a class="reference internal" href="#grammar-token-python-grammar-maybe_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">maybe_sequence_pattern</span></code></a>] "]"
| "(" [<a class="reference internal" href="#grammar-token-python-grammar-open_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">open_sequence_pattern</span></code></a>] ")"
<strong id="grammar-token-python-grammar-open_sequence_pattern">open_sequence_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-maybe_star_pattern"><code class="xref docutils literal notranslate"><span class="pre">maybe_star_pattern</span></code></a> "," [<a class="reference internal" href="#grammar-token-python-grammar-maybe_sequence_pattern"><code class="xref docutils literal notranslate"><span class="pre">maybe_sequence_pattern</span></code></a>]
<strong id="grammar-token-python-grammar-maybe_sequence_pattern">maybe_sequence_pattern</strong> ::= ",".<a class="reference internal" href="#grammar-token-python-grammar-maybe_star_pattern"><code class="xref docutils literal notranslate"><span class="pre">maybe_star_pattern</span></code></a>+ ","?
<strong id="grammar-token-python-grammar-maybe_star_pattern">maybe_star_pattern</strong> ::= <a class="reference internal" href="#grammar-token-python-grammar-star_pattern"><code class="xref docutils literal notranslate"><span class="pre">star_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-pattern"><code class="xref docutils literal notranslate"><span class="pre">pattern</span></code></a>
<strong id="grammar-token-python-grammar-star_pattern">star_pattern</strong> ::= "*" (<a class="reference internal" href="#grammar-token-python-grammar-capture_pattern"><code class="xref docutils literal notranslate"><span class="pre">capture_pattern</span></code></a> | <a class="reference internal" href="#grammar-token-python-grammar-wildcard_pattern"><code class="xref docutils literal notranslate"><span class="pre">wildcard_pattern</span></code></a>)
</pre>
<p>There is no difference if parentheses or square brackets
are used for sequence patterns (i.e. <code class="docutils literal notranslate"><span class="pre">(...)</span></code> vs <code class="docutils literal notranslate"><span class="pre">[...]</span></code> ).</p>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>A single pattern enclosed in parentheses without a trailing comma
(e.g. <code class="docutils literal notranslate"><span class="pre">(3</span> <span class="pre">|</span> <span class="pre">4)</span></code>) is a <a class="reference internal" href="#group-patterns"><span class="std std-ref">group pattern</span></a>.
While a single pattern enclosed in square brackets (e.g. <code class="docutils literal notranslate"><span class="pre">[3</span> <span class="pre">|</span> <span class="pre">4]</span></code>) is
still a sequence pattern.</p>
</div>
<p>At most one star subpattern may be in a sequence pattern. The star subpattern
may occur in any position. If no star subpattern is present, the sequence
pattern is a fixed-length sequence pattern; otherwise it is a variable-length
sequence pattern.</p>
<p>The following is the logical flow for matching a sequence pattern against a
subject value:</p>
<ol class="arabic">
<li><p>If the subject value is not a sequence <a class="footnote-reference brackets" href="#id21" id="id11" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>, the sequence pattern
fails.</p></li>
<li><p>If the subject value is an instance of <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">bytes</span></code> or <code class="docutils literal notranslate"><span class="pre">bytearray</span></code>
the sequence pattern fails.</p></li>
<li><p>The subsequent steps depend on whether the sequence pattern is fixed or
variable-length.</p>
<p>If the sequence pattern is fixed-length:</p>
<ol class="arabic simple">
<li><p>If the length of the subject sequence is not equal to the number of
subpatterns, the sequence pattern fails</p></li>
<li><p>Subpatterns in the sequence pattern are matched to their corresponding
items in the subject sequence from left to right. Matching stops as soon
as a subpattern fails. If all subpatterns succeed in matching their
corresponding item, the sequence pattern succeeds.</p></li>
</ol>
<p>Otherwise, if the sequence pattern is variable-length:</p>
<ol class="arabic simple">
<li><p>If the length of the subject sequence is less than the number of non-star
subpatterns, the sequence pattern fails.</p></li>
<li><p>The leading non-star subpatterns are matched to their corresponding items
as for fixed-length sequences.</p></li>
<li><p>If the previous step succeeds, the star subpattern matches a list formed
of the remaining subject items, excluding the remaining items
corresponding to non-star subpatterns following the star subpattern.</p></li>
<li><p>Remaining non-star subpatterns are matched to their corresponding subject
items, as for a fixed-length sequence.</p></li>
</ol>
<div class="admonition note">
<p class="admonition-title">備註</p>
<p>The length of the subject sequence is obtained via
<a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> (i.e. via the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> protocol). This length may be
cached by the interpreter in a similar manner as
<a class="reference internal" href="#value-patterns"><span class="std std-ref">value patterns</span></a>.</p>
</div>
</li>
</ol>
<p>In simple terms <code class="docutils literal notranslate"><span class="pre">[P1,</span> <span class="pre">P2,</span> <span class="pre">P3,</span></code> ... <code class="docutils literal notranslate"><span class="pre">,</span> <span class="pre">P<N>]</span></code> matches only if all the following
happens:</p>