-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontrolflow.html
1716 lines (1703 loc) · 62.6 KB
/
controlflow.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 xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=yes"
/>
<title>controlflow</title>
<style type="text/css">
code {
white-space: pre-wrap;
}
span.smallcaps {
font-variant: small-caps;
}
span.underline {
text-decoration: underline;
}
div.column {
display: inline-block;
vertical-align: top;
width: 50%;
}
</style>
</head>
<body>
<h3 id="navigation">Navigation</h3>
<ul>
<li>
<a href="https://docs.python.org/3/genindex.html" title="General Index"
>index</a
>
</li>
<li>
<a
href="https://docs.python.org/3/py-modindex.html"
title="Python Module Index"
>modules</a
>
|
</li>
<li>
<a href="datastructures.html" title="5. Data Structures">next</a> |
</li>
<li>
<a
href="introduction.html"
title="3. An Informal Introduction to Python"
>previous</a
>
|
</li>
<li><img src="../_static/py.png" /></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<a href="https://docs.python.org/3/index.html">3.9.5 Documentation</a> »
</li>
<li><a href="index.html">The Python Tutorial</a> »</li>
<li></li>
</ul>
<p><span id="tut-morecontrol"></span></p>
<h1 id="more-control-flow-tools">
<span class="section-number">4. </span>More Control Flow Tools<a
href="#more-control-flow-tools"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h1>
<p>
Besides the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#while"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>while</code
></a
>
statement just introduced, Python uses the usual flow control statements
known from other languages, with some twists.
</p>
<p><span id="tut-if"></span></p>
<h2 id="if-statements">
<span class="section-number">4.1. </span><code>if</code> Statements<a
href="#if-statements"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Perhaps the most well-known statement type is the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#if"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>if</code
></a
>
statement. For example:
</p>
<pre><code>>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More</code></pre>
<p>
There can be zero or more
<a
href="https://docs.python.org/3/reference/compound_stmts.html#elif"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>elif</code
></a
>
parts, and the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#else"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>else</code
></a
>
part is optional. The keyword ‘<code>elif</code>’ is short for ‘else if’,
and is useful to avoid excessive indentation. An <code>if</code> …
<code>elif</code> … <code>elif</code> … sequence is a substitute for the
<code>switch</code> or <code>case</code> statements found in other
languages.
</p>
<p><span id="tut-for"></span></p>
<h2 id="for-statements">
<span class="section-number">4.2. </span><code>for</code> Statements<a
href="#for-statements"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/compound_stmts.html#for"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>for</code
></a
>
statement in Python differs a bit from what you may be used to in C or
Pascal. Rather than always iterating over an arithmetic progression of
numbers (like in Pascal), or giving the user the ability to define both
the iteration step and halting condition (as C), Python’s
<code>for</code> statement iterates over the items of any sequence (a list
or a string), in the order that they appear in the sequence. For example
(no pun intended):
</p>
<pre><code>>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12</code></pre>
<p>
Code that modifies a collection while iterating over that same collection
can be tricky to get right. Instead, it is usually more straight-forward
to loop over a copy of the collection or to create a new collection:
</p>
<pre><code># Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status</code></pre>
<p><span id="tut-range"></span></p>
<h2 id="the-range-function">
<span class="section-number">4.3. </span>The
<a
href="https://docs.python.org/3/library/stdtypes.html#range"
class="reference internal"
title="range"
><code class="sourceCode python"
><span class="bu">range</span>()</code
></a
>
Function<a
href="#the-range-function"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
If you do need to iterate over a sequence of numbers, the built-in
function
<a
href="https://docs.python.org/3/library/stdtypes.html#range"
class="reference internal"
title="range"
><code class="sourceCode python"
><span class="bu">range</span>()</code
></a
>
comes in handy. It generates arithmetic progressions:
</p>
<pre><code>>>> for i in range(5):
... print(i)
...
0
1
2
3
4</code></pre>
<p>
The given end point is never part of the generated sequence;
<code>range(10)</code> generates 10 values, the legal indices for items of
a sequence of length 10. It is possible to let the range start at another
number, or to specify a different increment (even negative; sometimes this
is called the ‘step’):
</p>
<pre><code>range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70</code></pre>
<p>
To iterate over the indices of a sequence, you can combine
<a
href="https://docs.python.org/3/library/stdtypes.html#range"
class="reference internal"
title="range"
><code class="sourceCode python"
><span class="bu">range</span>()</code
></a
>
and
<a
href="https://docs.python.org/3/library/functions.html#len"
class="reference internal"
title="len"
><code class="sourceCode python"><span class="bu">len</span>()</code></a
>
as follows:
</p>
<pre><code>>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb</code></pre>
<p>
In most such cases, however, it is convenient to use the
<a
href="https://docs.python.org/3/library/functions.html#enumerate"
class="reference internal"
title="enumerate"
><code class="sourceCode python"
><span class="bu">enumerate</span>()</code
></a
>
function, see
<a href="datastructures.html#tut-loopidioms" class="reference internal"
><span class="std std-ref">Looping Techniques</span></a
>.
</p>
<p>A strange thing happens if you just print a range:</p>
<pre><code>>>> print(range(10))
range(0, 10)</code></pre>
<p>
In many ways the object returned by
<a
href="https://docs.python.org/3/library/stdtypes.html#range"
class="reference internal"
title="range"
><code class="sourceCode python"
><span class="bu">range</span>()</code
></a
>
behaves as if it is a list, but in fact it isn’t. It is an object which
returns the successive items of the desired sequence when you iterate over
it, but it doesn’t really make the list, thus saving space.
</p>
<p>
We say such an object is
<a
href="https://docs.python.org/3/glossary.html#term-iterable"
class="reference internal"
><span class="xref std std-term">iterable</span></a
>, that is, suitable as a target for functions and constructs that expect
something from which they can obtain successive items until the supply is
exhausted. We have seen that the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#for"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>for</code
></a
>
statement is such a construct, while an example of a function that takes
an iterable is
<a
href="https://docs.python.org/3/library/functions.html#sum"
class="reference internal"
title="sum"
><code class="sourceCode python"><span class="bu">sum</span>()</code></a
>:
</p>
<pre><code>>>> sum(range(4)) # 0 + 1 + 2 + 3
6</code></pre>
<p>
Later we will see more functions that return iterables and take iterables
as arguments. Lastly, maybe you are curious about how to get a list from a
range. Here is the solution:
</p>
<pre><code>>>> list(range(4))
[0, 1, 2, 3]</code></pre>
<p>
In chapter
<a href="datastructures.html#tut-structures" class="reference internal"
><span class="std std-ref">Data Structures</span></a
>, we will discuss in more detail about
<a
href="https://docs.python.org/3/library/stdtypes.html#list"
class="reference internal"
title="list"
><code class="sourceCode python"
><span class="bu">list</span>()</code
></a
>.
</p>
<p><span id="tut-break"></span></p>
<h2 id="break-and-continue-statements-and-else-clauses-on-loops">
<span class="section-number">4.4. </span><code>break</code> and
<code>continue</code> Statements, and <code>else</code> Clauses on Loops<a
href="#break-and-continue-statements-and-else-clauses-on-loops"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#break"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>break</code
></a
>
statement, like in C, breaks out of the innermost enclosing
<a
href="https://docs.python.org/3/reference/compound_stmts.html#for"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>for</code
></a
>
or
<a
href="https://docs.python.org/3/reference/compound_stmts.html#while"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>while</code
></a
>
loop.
</p>
<p>
Loop statements may have an <code>else</code> clause; it is executed when
the loop terminates through exhaustion of the iterable (with
<a
href="https://docs.python.org/3/reference/compound_stmts.html#for"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>for</code
></a
>) or when the condition becomes false (with
<a
href="https://docs.python.org/3/reference/compound_stmts.html#while"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>while</code
></a
>), but not when the loop is terminated by a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#break"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>break</code
></a
>
statement. This is exemplified by the following loop, which searches for
prime numbers:
</p>
<pre><code>>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3</code></pre>
<p>
(Yes, this is the correct code. Look closely: the <code>else</code> clause
belongs to the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#for"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>for</code
></a
>
loop, <strong>not</strong> the
<a
href="https://docs.python.org/3/reference/compound_stmts.html#if"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>if</code
></a
>
statement.)
</p>
<p>
When used with a loop, the <code>else</code> clause has more in common
with the <code>else</code> clause of a
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement than it does with that of
<a
href="https://docs.python.org/3/reference/compound_stmts.html#if"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>if</code
></a
>
statements: a
<a
href="https://docs.python.org/3/reference/compound_stmts.html#try"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>try</code
></a
>
statement’s <code>else</code> clause runs when no exception occurs, and a
loop’s <code>else</code> clause runs when no <code>break</code> occurs.
For more on the <code>try</code> statement and exceptions, see
<a href="errors.html#tut-handling" class="reference internal"
><span class="std std-ref">Handling Exceptions</span></a
>.
</p>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#continue"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>continue</code
></a
>
statement, also borrowed from C, continues with the next iteration of the
loop:
</p>
<pre><code>>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9</code></pre>
<p><span id="tut-pass"></span></p>
<h2 id="pass-statements">
<span class="section-number">4.5. </span><code>pass</code> Statements<a
href="#pass-statements"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#pass"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>pass</code
></a
>
statement does nothing. It can be used when a statement is required
syntactically but the program requires no action. For example:
</p>
<pre><code>>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...</code></pre>
<p>This is commonly used for creating minimal classes:</p>
<pre><code>>>> class MyEmptyClass:
... pass
...</code></pre>
<p>
Another place
<a
href="https://docs.python.org/3/reference/simple_stmts.html#pass"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>pass</code
></a
>
can be used is as a place-holder for a function or conditional body when
you are working on new code, allowing you to keep thinking at a more
abstract level. The <code>pass</code> is silently ignored:
</p>
<pre><code>>>> def initlog(*args):
... pass # Remember to implement this!
...</code></pre>
<p><span id="tut-functions"></span></p>
<h2 id="defining-functions">
<span class="section-number">4.6. </span>Defining Functions<a
href="#defining-functions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
We can create a function that writes the Fibonacci series to an arbitrary
boundary:
</p>
<pre><code>>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597</code></pre>
<p>
The keyword
<a
href="https://docs.python.org/3/reference/compound_stmts.html#def"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>def</code
></a
>
introduces a function <em>definition</em>. It must be followed by the
function name and the parenthesized list of formal parameters. The
statements that form the body of the function start at the next line, and
must be indented.
</p>
<p>
The first statement of the function body can optionally be a string
literal; this string literal is the function’s documentation string, or
<em>docstring</em>. (More about docstrings can be found in the section
<a href="#tut-docstrings" class="reference internal"
><span class="std std-ref">Documentation Strings</span></a
>.) There are tools which use docstrings to automatically produce online
or printed documentation, or to let the user interactively browse through
code; it’s good practice to include docstrings in code that you write, so
make a habit of it.
</p>
<p>
The <em>execution</em> of a function introduces a new symbol table used
for the local variables of the function. More precisely, all variable
assignments in a function store the value in the local symbol table;
whereas variable references first look in the local symbol table, then in
the local symbol tables of enclosing functions, then in the global symbol
table, and finally in the table of built-in names. Thus, global variables
and variables of enclosing functions cannot be directly assigned a value
within a function (unless, for global variables, named in a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#global"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>global</code
></a
>
statement, or, for variables of enclosing functions, named in a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#nonlocal"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>nonlocal</code
></a
>
statement), although they may be referenced.
</p>
<p>
The actual parameters (arguments) to a function call are introduced in the
local symbol table of the called function when it is called; thus,
arguments are passed using <em>call by value</em> (where the
<em>value</em> is always an object <em>reference</em>, not the value of
the object).
<a href="#id2" id="id1" class="footnote-reference brackets">1</a> When a
function calls another function, or calls itself recursively, a new local
symbol table is created for that call.
</p>
<p>
A function definition associates the function name with the function
object in the current symbol table. The interpreter recognizes the object
pointed to by that name as a user-defined function. Other names can also
point to that same function object and can also be used to access the
function:
</p>
<pre><code>>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89</code></pre>
<p>
Coming from other languages, you might object that <code>fib</code> is not
a function but a procedure since it doesn’t return a value. In fact, even
functions without a
<a
href="https://docs.python.org/3/reference/simple_stmts.html#return"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>return</code
></a
>
statement do return a value, albeit a rather boring one. This value is
called <code>None</code> (it’s a built-in name). Writing the value
<code>None</code> is normally suppressed by the interpreter if it would be
the only value written. You can see it if you really want to using
<a
href="https://docs.python.org/3/library/functions.html#print"
class="reference internal"
title="print"
><code class="sourceCode python"
><span class="bu">print</span>()</code
></a
>:
</p>
<pre><code>>>> fib(0)
>>> print(fib(0))
None</code></pre>
<p>
It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:
</p>
<pre><code>>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</code></pre>
<p>This example, as usual, demonstrates some new Python features:</p>
<ul>
<li>
<p>
The
<a
href="https://docs.python.org/3/reference/simple_stmts.html#return"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>return</code
></a
>
statement returns with a value from a function.
<code>return</code> without an expression argument returns
<code>None</code>. Falling off the end of a function also returns
<code>None</code>.
</p>
</li>
<li>
<p>
The statement <code>result.append(a)</code> calls a <em>method</em> of
the list object <code>result</code>. A method is a function that
‘belongs’ to an object and is named <code>obj.methodname</code>, where
<code>obj</code> is some object (this may be an expression), and
<code>methodname</code> is the name of a method that is defined by the
object’s type. Different types define different methods. Methods of
different types may have the same name without causing ambiguity. (It
is possible to define your own object types and methods, using
<em>classes</em>, see
<a href="classes.html#tut-classes" class="reference internal"
><span class="std std-ref">Classes</span></a
>) The method <code>append()</code> shown in the example is defined
for list objects; it adds a new element at the end of the list. In
this example it is equivalent to <code>result = result + [a]</code>,
but more efficient.
</p>
</li>
</ul>
<p><span id="tut-defining"></span></p>
<h2 id="more-on-defining-functions">
<span class="section-number">4.7. </span>More on Defining Functions<a
href="#more-on-defining-functions"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
It is also possible to define functions with a variable number of
arguments. There are three forms, which can be combined.
</p>
<p><span id="tut-defaultargs"></span></p>
<h3 id="default-argument-values">
<span class="section-number">4.7.1. </span>Default Argument Values<a
href="#default-argument-values"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
The most useful form is to specify a default value for one or more
arguments. This creates a function that can be called with fewer arguments
than it is defined to allow. For example:
</p>
<pre><code>def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)</code></pre>
<p>This function can be called in several ways:</p>
<ul>
<li>
<p>
giving only the mandatory argument:
<code>ask_ok('Do you really want to quit?')</code>
</p>
</li>
<li>
<p>
giving one of the optional arguments:
<code>ask_ok('OK to overwrite the file?', 2)</code>
</p>
</li>
<li>
<p>
or even giving all arguments:
<code
>ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or
no!')</code
>
</p>
</li>
</ul>
<p>
This example also introduces the
<a
href="https://docs.python.org/3/reference/expressions.html#in"
class="reference internal"
><code class="xref std std-keyword docutils literal notranslate"
>in</code
></a
>
keyword. This tests whether or not a sequence contains a certain value.
</p>
<p>
The default values are evaluated at the point of function definition in
the <em>defining</em> scope, so that
</p>
<pre><code>i = 5
def f(arg=i):
print(arg)
i = 6
f()</code></pre>
<p>will print <code>5</code>.</p>
<p>
<strong>Important warning:</strong> The default value is evaluated only
once. This makes a difference when the default is a mutable object such as
a list, dictionary, or instances of most classes. For example, the
following function accumulates the arguments passed to it on subsequent
calls:
</p>
<pre><code>def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))</code></pre>
<p>This will print</p>
<pre><code>[1]
[1, 2]
[1, 2, 3]</code></pre>
<p>
If you don’t want the default to be shared between subsequent calls, you
can write the function like this instead:
</p>
<pre><code>def f(a, L=None):
if L is None:
L = []
L.append(a)
return L</code></pre>
<p><span id="tut-keywordargs"></span></p>
<h3 id="keyword-arguments">
<span class="section-number">4.7.2. </span>Keyword Arguments<a
href="#keyword-arguments"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
Functions can also be called using
<a
href="https://docs.python.org/3/glossary.html#term-keyword-argument"
class="reference internal"
><span class="xref std std-term">keyword arguments</span></a
>
of the form <code>kwarg=value</code>. For instance, the following
function:
</p>
<pre><code>def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")</code></pre>
<p>
accepts one required argument (<code>voltage</code>) and three optional
arguments (<code>state</code>, <code>action</code>, and
<code>type</code>). This function can be called in any of the following
ways:
</p>
<pre><code>parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword</code></pre>
<p>but all the following calls would be invalid:</p>
<pre><code>parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument</code></pre>
<p>
In a function call, keyword arguments must follow positional arguments.
All the keyword arguments passed must match one of the arguments accepted
by the function (e.g. <code>actor</code> is not a valid argument for the
<code>parrot</code> function), and their order is not important. This also
includes non-optional arguments (e.g. <code>parrot(voltage=1000)</code> is
valid too). No argument may receive a value more than once. Here’s an
example that fails due to this restriction:
</p>
<pre><code>>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'</code></pre>
<p>
When a final formal parameter of the form <code>**name</code> is present,
it receives a dictionary (see
<a
href="https://docs.python.org/3/library/stdtypes.html#typesmapping"
class="reference internal"
><span class="std std-ref">Mapping Types — dict</span></a
>) containing all keyword arguments except for those corresponding to a
formal parameter. This may be combined with a formal parameter of the form
<code>*name</code> (described in the next subsection) which receives a
<a href="datastructures.html#tut-tuples" class="reference internal"
><span class="std std-ref">tuple</span></a
>
containing the positional arguments beyond the formal parameter list.
(<code>*name</code> must occur before <code>**name</code>.) For example,
if we define a function like this:
</p>
<pre><code>def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])</code></pre>
<p>It could be called like this:</p>
<pre><code>cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")</code></pre>
<p>and of course it would print:</p>
<pre><code>-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch</code></pre>
<p>
Note that the order in which the keyword arguments are printed is
guaranteed to match the order in which they were provided in the function
call.
</p>
<h3 id="special-parameters">
<span class="section-number">4.7.3. </span>Special parameters<a
href="#special-parameters"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
By default, arguments may be passed to a Python function either by
position or explicitly by keyword. For readability and performance, it
makes sense to restrict the way arguments can be passed so that a
developer need only look at the function definition to determine if items
are passed by position, by position or keyword, or by keyword.
</p>
<p>A function definition may look like:</p>
<pre><code>def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
| | |
| Positional or keyword |
| - Keyword only
-- Positional only</code></pre>
<p>
where <code>/</code> and <code>*</code> are optional. If used, these
symbols indicate the kind of parameter by how the arguments may be passed
to the function: positional-only, positional-or-keyword, and keyword-only.
Keyword parameters are also referred to as named parameters.
</p>
<h4 id="positional-or-keyword-arguments">
<span class="section-number">4.7.3.1. </span>Positional-or-Keyword
Arguments<a
href="#positional-or-keyword-arguments"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h4>
<p>
If <code>/</code> and <code>*</code> are not present in the function
definition, arguments may be passed to a function by position or by
keyword.
</p>
<h4 id="positional-only-parameters">
<span class="section-number">4.7.3.2. </span>Positional-Only Parameters<a
href="#positional-only-parameters"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h4>
<p>
Looking at this in a bit more detail, it is possible to mark certain
parameters as <em>positional-only</em>. If <em>positional-only</em>, the
parameters’ order matters, and the parameters cannot be passed by keyword.