-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathintroduction.html
916 lines (916 loc) · 33.9 KB
/
introduction.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
<!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>introduction</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="controlflow.html" title="4. More Control Flow Tools">next</a> |
</li>
<li>
<a href="interpreter.html" title="2. Using the Python Interpreter"
>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-informal"></span></p>
<h1 id="an-informal-introduction-to-python">
<span class="section-number">3. </span>An Informal Introduction to
Python<a
href="#an-informal-introduction-to-python"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h1>
<p>
In the following examples, input and output are distinguished by the
presence or absence of prompts (<a
href="https://docs.python.org/3/glossary.html#term-0"
class="reference internal"
><span class="xref std std-term">>>></span></a
>
and
<a
href="https://docs.python.org/3/glossary.html#term-1"
class="reference internal"
><span class="xref std std-term">…</span></a
>): to repeat the example, you must type everything after the prompt, when
the prompt appears; lines that do not begin with a prompt are output from
the interpreter. Note that a secondary prompt on a line by itself in an
example means you must type a blank line; this is used to end a multi-line
command.
</p>
<p>
Many of the examples in this manual, even those entered at the interactive
prompt, include comments. Comments in Python start with the hash
character, <code>#</code>, and extend to the end of the physical line. A
comment may appear at the start of a line or following whitespace or code,
but not within a string literal. A hash character within a string literal
is just a hash character. Since comments are to clarify code and are not
interpreted by Python, they may be omitted when typing in examples.
</p>
<p>Some examples:</p>
<pre><code># this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."</code></pre>
<p><span id="tut-calculator"></span></p>
<h2 id="using-python-as-a-calculator">
<span class="section-number">3.1. </span>Using Python as a Calculator<a
href="#using-python-as-a-calculator"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Let’s try some simple Python commands. Start the interpreter and wait for
the primary prompt, <code>>>></code>. (It shouldn’t take long.)
</p>
<p><span id="tut-numbers"></span></p>
<h3 id="numbers">
<span class="section-number">3.1.1. </span>Numbers<a
href="#numbers"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
The interpreter acts as a simple calculator: you can type an expression at
it and it will write the value. Expression syntax is straightforward: the
operators <code>+</code>, <code>-</code>, <code>*</code> and
<code>/</code> work just like in most other languages (for example, Pascal
or C); parentheses (<code>()</code>) can be used for grouping. For
example:
</p>
<pre><code>>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6</code></pre>
<p>
The integer numbers (e.g. <code>2</code>, <code>4</code>, <code>20</code>)
have type
<a
href="https://docs.python.org/3/library/functions.html#int"
class="reference internal"
title="int"
><code class="sourceCode python"><span class="bu">int</span></code></a
>, the ones with a fractional part (e.g. <code>5.0</code>,
<code>1.6</code>) have type
<a
href="https://docs.python.org/3/library/functions.html#float"
class="reference internal"
title="float"
><code class="sourceCode python"><span class="bu">float</span></code></a
>. We will see more about numeric types later in the tutorial.
</p>
<p>
Division (<code>/</code>) always returns a float. To do
<a
href="https://docs.python.org/3/glossary.html#term-floor-division"
class="reference internal"
><span class="xref std std-term">floor division</span></a
>
and get an integer result (discarding any fractional result) you can use
the <code>//</code> operator; to calculate the remainder you can use
<code>%</code>:
</p>
<pre><code>>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17</code></pre>
<p>
With Python, it is possible to use the <code>**</code> operator to
calculate powers
<a href="#id3" id="id1" class="footnote-reference brackets">1</a>:
</p>
<pre><code>>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128</code></pre>
<p>
The equal sign (<code>=</code>) is used to assign a value to a variable.
Afterwards, no result is displayed before the next interactive prompt:
</p>
<pre><code>>>> width = 20
>>> height = 5 * 9
>>> width * height
900</code></pre>
<p>
If a variable is not “defined” (assigned a value), trying to use it will
give you an error:
</p>
<pre><code>>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined</code></pre>
<p>
There is full support for floating point; operators with mixed type
operands convert the integer operand to floating point:
</p>
<pre><code>>>> 4 * 3.75 - 1
14.0</code></pre>
<p>
In interactive mode, the last printed expression is assigned to the
variable <code>_</code>. This means that when you are using Python as a
desk calculator, it is somewhat easier to continue calculations, for
example:
</p>
<pre><code>>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06</code></pre>
<p>
This variable should be treated as read-only by the user. Don’t explicitly
assign a value to it — you would create an independent local variable with
the same name masking the built-in variable with its magic behavior.
</p>
<p>
In addition to
<a
href="https://docs.python.org/3/library/functions.html#int"
class="reference internal"
title="int"
><code class="sourceCode python"><span class="bu">int</span></code></a
>
and
<a
href="https://docs.python.org/3/library/functions.html#float"
class="reference internal"
title="float"
><code class="sourceCode python"><span class="bu">float</span></code></a
>, Python supports other types of numbers, such as
<a
href="https://docs.python.org/3/library/decimal.html#decimal.Decimal"
class="reference internal"
title="decimal.Decimal"
><code class="sourceCode python">Decimal</code></a
>
and
<a
href="https://docs.python.org/3/library/fractions.html#fractions.Fraction"
class="reference internal"
title="fractions.Fraction"
><code class="sourceCode python">Fraction</code></a
>. Python also has built-in support for
<a
href="https://docs.python.org/3/library/stdtypes.html#typesnumeric"
class="reference internal"
><span class="std std-ref">complex numbers</span></a
>, and uses the <code>j</code> or <code>J</code> suffix to indicate the
imaginary part (e.g. <code>3+5j</code>).
</p>
<p><span id="tut-strings"></span></p>
<h3 id="strings">
<span class="section-number">3.1.2. </span>Strings<a
href="#strings"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
Besides numbers, Python can also manipulate strings, which can be
expressed in several ways. They can be enclosed in single quotes
(<code>'...'</code>) or double quotes (<code>"..."</code>) with the same
result <a href="#id4" id="id2" class="footnote-reference brackets">2</a>.
<code>\</code> can be used to escape quotes:
</p>
<pre><code>>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'</code></pre>
<p>
In the interactive interpreter, the output string is enclosed in quotes
and special characters are escaped with backslashes. While this might
sometimes look different from the input (the enclosing quotes could
change), the two strings are equivalent. The string is enclosed in double
quotes if the string contains a single quote and no double quotes,
otherwise it is enclosed in single quotes. The
<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
>
function produces a more readable output, by omitting the enclosing quotes
and by printing escaped and special characters:
</p>
<pre><code>>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.</code></pre>
<p>
If you don’t want characters prefaced by <code>\</code> to be interpreted
as special characters, you can use <em>raw strings</em> by adding an
<code>r</code> before the first quote:
</p>
<pre><code>>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name</code></pre>
<p>
String literals can span multiple lines. One way is using triple-quotes:
<code>"""..."""</code> or <code>'''...'''</code>. End of lines are
automatically included in the string, but it’s possible to prevent this by
adding a <code>\</code> at the end of the line. The following example:
</p>
<pre><code>print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")</code></pre>
<p>
produces the following output (note that the initial newline is not
included):
</p>
<pre><code>Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to</code></pre>
<p>
Strings can be concatenated (glued together) with the
<code>+</code> operator, and repeated with <code>*</code>:
</p>
<pre><code>>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'</code></pre>
<p>
Two or more <em>string literals</em> (i.e. the ones enclosed between
quotes) next to each other are automatically concatenated.
</p>
<pre><code>>>> 'Py' 'thon'
'Python'</code></pre>
<p>
This feature is particularly useful when you want to break long strings:
</p>
<pre><code>>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'</code></pre>
<p>
This only works with two literals though, not with variables or
expressions:
</p>
<pre><code>>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
File "<stdin>", line 1
prefix 'thon'
^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
File "<stdin>", line 1
('un' * 3) 'ium'
^
SyntaxError: invalid syntax</code></pre>
<p>
If you want to concatenate variables or a variable and a literal, use
<code>+</code>:
</p>
<pre><code>>>> prefix + 'thon'
'Python'</code></pre>
<p>
Strings can be <em>indexed</em> (subscripted), with the first character
having index 0. There is no separate character type; a character is simply
a string of size one:
</p>
<pre><code>>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'</code></pre>
<p>
Indices may also be negative numbers, to start counting from the right:
</p>
<pre><code>>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'</code></pre>
<p>Note that since -0 is the same as 0, negative indices start from -1.</p>
<p>
In addition to indexing, <em>slicing</em> is also supported. While
indexing is used to obtain individual characters, <em>slicing</em> allows
you to obtain substring:
</p>
<pre><code>>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'</code></pre>
<p>
Note how the start is always included, and the end always excluded. This
makes sure that <code>s[:i] + s[i:]</code> is always equal to
<code>s</code>:
</p>
<pre><code>>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'</code></pre>
<p>
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
</p>
<pre><code>>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:] # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'</code></pre>
<p>
One way to remember how slices work is to think of the indices as pointing
<em>between</em> characters, with the left edge of the first character
numbered 0. Then the right edge of the last character of a string of
<em>n</em> characters has index <em>n</em>, for example:
</p>
<pre><code> +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1</code></pre>
<p>
The first row of numbers gives the position of the indices 0…6 in the
string; the second row gives the corresponding negative indices. The slice
from <em>i</em> to <em>j</em> consists of all characters between the edges
labeled <em>i</em> and <em>j</em>, respectively.
</p>
<p>
For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds. For example, the length of
<code>word[1:3]</code> is 2.
</p>
<p>Attempting to use an index that is too large will result in an error:</p>
<pre><code>>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range</code></pre>
<p>
However, out of range slice indexes are handled gracefully when used for
slicing:
</p>
<pre><code>>>> word[4:42]
'on'
>>> word[42:]
''</code></pre>
<p>
Python strings cannot be changed — they are
<a
href="https://docs.python.org/3/glossary.html#term-immutable"
class="reference internal"
><span class="xref std std-term">immutable</span></a
>. Therefore, assigning to an indexed position in the string results in an
error:
</p>
<pre><code>>>> word[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment</code></pre>
<p>If you need a different string, you should create a new one:</p>
<pre><code>>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'</code></pre>
<p>
The built-in function
<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
>
returns the length of a string:
</p>
<pre><code>>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34</code></pre>
<p>See also</p>
<p>
<a
href="https://docs.python.org/3/library/stdtypes.html#textseq"
class="reference internal"
><span class="std std-ref">Text Sequence Type — str</span></a
><br />
Strings are examples of <em>sequence types</em>, and support the common
operations supported by such types.
</p>
<p>
<a
href="https://docs.python.org/3/library/stdtypes.html#string-methods"
class="reference internal"
><span class="std std-ref">String Methods</span></a
><br />
Strings support a large number of methods for basic transformations and
searching.
</p>
<p>
<a
href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings"
class="reference internal"
><span class="std std-ref">Formatted string literals</span></a
><br />
String literals that have embedded expressions.
</p>
<p>
<a
href="https://docs.python.org/3/library/string.html#formatstrings"
class="reference internal"
><span class="std std-ref">Format String Syntax</span></a
><br />
Information about string formatting with
<a
href="https://docs.python.org/3/library/stdtypes.html#str.format"
class="reference internal"
title="str.format"
><code class="sourceCode python"
><span class="bu">str</span>.<span class="bu">format</span>()</code
></a
>.
</p>
<p>
<a
href="https://docs.python.org/3/library/stdtypes.html#old-string-formatting"
class="reference internal"
><span class="std std-ref">printf-style String Formatting</span></a
><br />
The old formatting operations invoked when strings are the left operand of
the <code>%</code> operator are described in more detail here.
</p>
<p><span id="tut-lists"></span></p>
<h3 id="lists">
<span class="section-number">3.1.3. </span>Lists<a
href="#lists"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h3>
<p>
Python knows a number of <em>compound</em> data types, used to group
together other values. The most versatile is the <em>list</em>, which can
be written as a list of comma-separated values (items) between square
brackets. Lists might contain items of different types, but usually the
items all have the same type.
</p>
<pre><code>>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]</code></pre>
<p>
Like strings (and all other built-in
<a
href="https://docs.python.org/3/glossary.html#term-sequence"
class="reference internal"
><span class="xref std std-term">sequence</span></a
>
types), lists can be indexed and sliced:
</p>
<pre><code>>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]</code></pre>
<p>
All slice operations return a new list containing the requested elements.
This means that the following slice returns a
<a
href="https://docs.python.org/3/library/copy.html#shallow-vs-deep-copy"
class="reference internal"
><span class="std std-ref">shallow copy</span></a
>
of the list:
</p>
<pre><code>>>> squares[:]
[1, 4, 9, 16, 25]</code></pre>
<p>Lists also support operations like concatenation:</p>
<pre><code>>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</code></pre>
<p>
Unlike strings, which are
<a
href="https://docs.python.org/3/glossary.html#term-immutable"
class="reference internal"
><span class="xref std std-term">immutable</span></a
>, lists are a
<a
href="https://docs.python.org/3/glossary.html#term-mutable"
class="reference internal"
><span class="xref std std-term">mutable</span></a
>
type, i.e. it is possible to change their content:
</p>
<pre><code>>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]</code></pre>
<p>
You can also add new items at the end of the list, by using the
<code>append()</code> <em>method</em> (we will see more about methods
later):
</p>
<pre><code>>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]</code></pre>
<p>
Assignment to slices is also possible, and this can even change the size
of the list or clear it entirely:
</p>
<pre><code>>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]</code></pre>
<p>
The built-in function
<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
>
also applies to lists:
</p>
<pre><code>>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4</code></pre>
<p>
It is possible to nest lists (create lists containing other lists), for
example:
</p>
<pre><code>>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'</code></pre>
<p><span id="tut-firststeps"></span></p>
<h2 id="first-steps-towards-programming">
<span class="section-number">3.2. </span>First Steps Towards Programming<a
href="#first-steps-towards-programming"
class="headerlink"
title="Permalink to this headline"
>¶</a
>
</h2>
<p>
Of course, we can use Python for more complicated tasks than adding two
and two together. For instance, we can write an initial sub-sequence of
the
<a
href="https://en.wikipedia.org/wiki/Fibonacci_number"
class="reference external"
>Fibonacci series</a
>
as follows:
</p>
<pre><code>>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8</code></pre>
<p>This example introduces several new features.</p>
<ul>
<li>
<p>
The first line contains a <em>multiple assignment</em>: the variables
<code>a</code> and <code>b</code> simultaneously get the new values 0
and 1. On the last line this is used again, demonstrating that the
expressions on the right-hand side are all evaluated first before any
of the assignments take place. The right-hand side expressions are
evaluated from the left to the right.
</p>
</li>
<li>
<p>
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
>
loop executes as long as the condition (here: <code>a < 10</code>)
remains true. In Python, like in C, any non-zero integer value is
true; zero is false. The condition may also be a string or list value,
in fact any sequence; anything with a non-zero length is true, empty
sequences are false. The test used in the example is a simple
comparison. The standard comparison operators are written the same as
in C: <code><</code> (less than), <code>></code> (greater than),
<code>==</code> (equal to), <code><=</code> (less than or equal
to), <code>>=</code> (greater than or equal to) and
<code>!=</code> (not equal to).
</p>
</li>
<li>
<p>
The <em>body</em> of the loop is <em>indented</em>: indentation is
Python’s way of grouping statements. At the interactive prompt, you
have to type a tab or space(s) for each indented line. In practice you
will prepare more complicated input for Python with a text editor; all
decent text editors have an auto-indent facility. When a compound
statement is entered interactively, it must be followed by a blank
line to indicate completion (since the parser cannot guess when you
have typed the last line). Note that each line within a basic block
must be indented by the same amount.
</p>
</li>
<li>
<p>
The
<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
>
function writes the value of the argument(s) it is given. It differs
from just writing the expression you want to write (as we did earlier
in the calculator examples) in the way it handles multiple arguments,
floating point quantities, and strings. Strings are printed without
quotes, and a space is inserted between items, so you can format
things nicely, like this:
</p>
<pre><code>>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536</code></pre>
<p>
The keyword argument <em>end</em> can be used to avoid the newline
after the output, or end the output with a different string:
</p>
<pre><code>>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,</code></pre>
</li>
</ul>
<p>Footnotes</p>
<p>
<span class="brackets"><a href="#id1" class="fn-backref">1</a></span
><br />
Since <code>**</code> has higher precedence than <code>-</code>,
<code>-3**2</code> will be interpreted as <code>-(3**2)</code> and thus
result in <code>-9</code>. To avoid this and get <code>9</code>, you can
use <code>(-3)**2</code>.
</p>
<p>
<span class="brackets"><a href="#id2" class="fn-backref">2</a></span
><br />
Unlike other languages, special characters such as <code>\n</code> have
the same meaning with both single (<code>'...'</code>) and double
(<code>"..."</code>) quotes. The only difference between the two is that
within single quotes you don’t need to escape <code>"</code> (but you have
to escape <code>\'</code>) and vice versa.
</p>
<h3 id="table-of-contents">
<a href="https://docs.python.org/3/contents.html">Table of Contents</a>
</h3>
<ul>
<li>
<a href="#" class="reference internal"
>3. An Informal Introduction to Python</a
>
<ul>
<li>
<a href="#using-python-as-a-calculator" class="reference internal"
>3.1. Using Python as a Calculator</a
>
<ul>
<li>
<a href="#numbers" class="reference internal">3.1.1. Numbers</a>
</li>
<li>
<a href="#strings" class="reference internal">3.1.2. Strings</a>
</li>
<li>
<a href="#lists" class="reference internal">3.1.3. Lists</a>
</li>
</ul>
</li>
<li>
<a
href="#first-steps-towards-programming"
class="reference internal"
>3.2. First Steps Towards Programming</a
>
</li>
</ul>
</li>
</ul>
<h4 id="previous-topic">Previous topic</h4>
<p>
<a href="interpreter.html" title="previous chapter"
><span class="section-number">2. </span>Using the Python Interpreter</a
>
</p>
<h4 id="next-topic">Next topic</h4>
<p>
<a href="controlflow.html" title="next chapter"
><span class="section-number">4. </span>More Control Flow Tools</a
>
</p>
<h3 id="this-page">This Page</h3>
<ul>
<li><a href="https://docs.python.org/3/bugs.html">Report a Bug</a></li>
<li>
<a
href="https://github.com/python/cpython/blob/3.9/Doc/tutorial/introduction.rst"
>Show Source</a
>
</li>
</ul>
<h3 id="navigation-1">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="controlflow.html" title="4. More Control Flow Tools">next</a> |
</li>
<li>
<a href="interpreter.html" title="2. Using the Python Interpreter"
>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>
©
<a href="https://docs.python.org/3/copyright.html">Copyright</a>
2001-2021, Python Software Foundation.<br />
The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
</p>
<p>
Last updated on May 30, 2021.
<a href="https://docs.python.org/3/bugs.html">Found a bug</a>?<br />
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 2.4.4.
</p>
</body>
</html>