summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/tutorial%2Fintroduction.html
blob: ea5fbec05cb9197e4e9fde4ccd809d9c0bd18202 (plain)
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
 <span id="tut-informal"></span><h1> An Informal Introduction to Python</h1> <p>In the following examples, input and output are distinguished by the presence or absence of prompts (<a class="reference internal" href="../glossary#term-0"><span class="xref std std-term">&gt;&gt;&gt;</span></a> and <a class="reference internal" href="../glossary#term-..."><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>You can toggle the display of prompts and output by clicking on <code>&gt;&gt;&gt;</code> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.</p> <p id="index-0">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 data-language="python"># 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."
</pre> <section id="using-python-as-a-calculator"> <span id="tut-calculator"></span><h2>
<span class="section-number">3.1. </span>Using Python as a Calculator</h2> <p>Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, <code>&gt;&gt;&gt;</code>. (It shouldn’t take long.)</p> <section id="numbers"> <span id="tut-numbers"></span><h3>
<span class="section-number">3.1.1. </span>Numbers</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> can be used to perform arithmetic; parentheses (<code>()</code>) can be used for grouping. For example:</p> <pre data-language="python">&gt;&gt;&gt; 2 + 2
4
&gt;&gt;&gt; 50 - 5*6
20
&gt;&gt;&gt; (50 - 5*6) / 4
5.0
&gt;&gt;&gt; 8 / 5  # division always returns a floating point number
1.6
</pre> <p>The integer numbers (e.g. <code>2</code>, <code>4</code>, <code>20</code>) have type <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a>, the ones with a fractional part (e.g. <code>5.0</code>, <code>1.6</code>) have type <a class="reference internal" href="../library/functions#float" title="float"><code>float</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 class="reference internal" href="../glossary#term-floor-division"><span class="xref std std-term">floor division</span></a> and get an integer result you can use the <code>//</code> operator; to calculate the remainder you can use <code>%</code>:</p> <pre data-language="python">&gt;&gt;&gt; 17 / 3  # classic division returns a float
5.666666666666667
&gt;&gt;&gt;
&gt;&gt;&gt; 17 // 3  # floor division discards the fractional part
5
&gt;&gt;&gt; 17 % 3  # the % operator returns the remainder of the division
2
&gt;&gt;&gt; 5 * 3 + 2  # floored quotient * divisor + remainder
17
</pre> <p>With Python, it is possible to use the <code>**</code> operator to calculate powers <a class="footnote-reference brackets" href="#id3" id="id1">1</a>:</p> <pre data-language="python">&gt;&gt;&gt; 5 ** 2  # 5 squared
25
&gt;&gt;&gt; 2 ** 7  # 2 to the power of 7
128
</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 data-language="python">&gt;&gt;&gt; width = 20
&gt;&gt;&gt; height = 5 * 9
&gt;&gt;&gt; width * height
900
</pre> <p>If a variable is not “defined” (assigned a value), trying to use it will give you an error:</p> <pre data-language="python">&gt;&gt;&gt; n  # try to access an undefined variable
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
NameError: name 'n' is not defined
</pre> <p>There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:</p> <pre data-language="python">&gt;&gt;&gt; 4 * 3.75 - 1
14.0
</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 data-language="python">&gt;&gt;&gt; tax = 12.5 / 100
&gt;&gt;&gt; price = 100.50
&gt;&gt;&gt; price * tax
12.5625
&gt;&gt;&gt; price + _
113.0625
&gt;&gt;&gt; round(_, 2)
113.06
</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 class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> and <a class="reference internal" href="../library/functions#float" title="float"><code>float</code></a>, Python supports other types of numbers, such as <a class="reference internal" href="../library/decimal#decimal.Decimal" title="decimal.Decimal"><code>Decimal</code></a> and <a class="reference internal" href="../library/fractions#fractions.Fraction" title="fractions.Fraction"><code>Fraction</code></a>. Python also has built-in support for <a class="reference internal" href="../library/stdtypes#typesnumeric"><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> </section> <section id="text"> <span id="tut-strings"></span><h3>
<span class="section-number">3.1.2. </span>Text</h3> <p>Python can manipulate text (represented by type <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>, so-called “strings”) as well as numbers. This includes characters “<code>!</code>”, words “<code>rabbit</code>”, names “<code>Paris</code>”, sentences “<code>Got your back.</code>”, etc. “<code>Yay! :)</code>”. They can be enclosed in single quotes (<code>'...'</code>) or double quotes (<code>"..."</code>) with the same result <a class="footnote-reference brackets" href="#id4" id="id2">2</a>.</p> <pre data-language="python">&gt;&gt;&gt; 'spam eggs'  # single quotes
'spam eggs'
&gt;&gt;&gt; "Paris rabbit got your back :)! Yay!"  # double quotes
'Paris rabbit got your back :)! Yay!'
&gt;&gt;&gt; '1975'  # digits and numerals enclosed in quotes are also strings
'1975'
</pre> <p>To quote a quote, we need to “escape” it, by preceding it with <code>\</code>. Alternatively, we can use the other type of quotation marks:</p> <pre data-language="python">&gt;&gt;&gt; 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
&gt;&gt;&gt; "doesn't"  # ...or use double quotes instead
"doesn't"
&gt;&gt;&gt; '"Yes," they said.'
'"Yes," they said.'
&gt;&gt;&gt; "\"Yes,\" they said."
'"Yes," they said.'
&gt;&gt;&gt; '"Isn\'t," they said.'
'"Isn\'t," they said.'
</pre> <p>In the Python shell, the string definition and output string can look different. The <a class="reference internal" href="../library/functions#print" title="print"><code>print()</code></a> function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:</p> <pre data-language="python">&gt;&gt;&gt; s = 'First line.\nSecond line.'  # \n means newline
&gt;&gt;&gt; s  # without print(), special characters are included in the string
'First line.\nSecond line.'
&gt;&gt;&gt; print(s)  # with print(), special characters are interpreted, so \n produces new line
First line.
Second line.
</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 data-language="python">&gt;&gt;&gt; print('C:\some\name')  # here \n means newline!
C:\some
ame
&gt;&gt;&gt; print(r'C:\some\name')  # note the r before the quote
C:\some\name
</pre> <p>There is one subtle aspect to raw strings: a raw string may not end in an odd number of <code>\</code> characters; see <a class="reference internal" href="../faq/programming#faq-programming-raw-string-backslash"><span class="std std-ref">the FAQ entry</span></a> for more information and workarounds.</p> <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 data-language="python">print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
</pre> <p>produces the following output (note that the initial newline is not included):</p> <pre data-language="text">Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
</pre> <p>Strings can be concatenated (glued together) with the <code>+</code> operator, and repeated with <code>*</code>:</p> <pre data-language="python">&gt;&gt;&gt; # 3 times 'un', followed by 'ium'
&gt;&gt;&gt; 3 * 'un' + 'ium'
'unununium'
</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 data-language="python">&gt;&gt;&gt; 'Py' 'thon'
'Python'
</pre> <p>This feature is particularly useful when you want to break long strings:</p> <pre data-language="python">&gt;&gt;&gt; text = ('Put several strings within parentheses '
...         'to have them joined together.')
&gt;&gt;&gt; text
'Put several strings within parentheses to have them joined together.'
</pre> <p>This only works with two literals though, not with variables or expressions:</p> <pre data-language="python">&gt;&gt;&gt; prefix = 'Py'
&gt;&gt;&gt; prefix 'thon'  # can't concatenate a variable and a string literal
  File "&lt;stdin&gt;", line 1
    prefix 'thon'
           ^^^^^^
SyntaxError: invalid syntax
&gt;&gt;&gt; ('un' * 3) 'ium'
  File "&lt;stdin&gt;", line 1
    ('un' * 3) 'ium'
               ^^^^^
SyntaxError: invalid syntax
</pre> <p>If you want to concatenate variables or a variable and a literal, use <code>+</code>:</p> <pre data-language="python">&gt;&gt;&gt; prefix + 'thon'
'Python'
</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 data-language="python">&gt;&gt;&gt; word = 'Python'
&gt;&gt;&gt; word[0]  # character in position 0
'P'
&gt;&gt;&gt; word[5]  # character in position 5
'n'
</pre> <p>Indices may also be negative numbers, to start counting from the right:</p> <pre data-language="python">&gt;&gt;&gt; word[-1]  # last character
'n'
&gt;&gt;&gt; word[-2]  # second-last character
'o'
&gt;&gt;&gt; word[-6]
'P'
</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 a substring:</p> <pre data-language="python">&gt;&gt;&gt; word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
&gt;&gt;&gt; word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
</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 data-language="python">&gt;&gt;&gt; word[:2]   # character from the beginning to position 2 (excluded)
'Py'
&gt;&gt;&gt; word[4:]   # characters from position 4 (included) to the end
'on'
&gt;&gt;&gt; word[-2:]  # characters from the second-last (included) to the end
'on'
</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 data-language="python">&gt;&gt;&gt; word[:2] + word[2:]
'Python'
&gt;&gt;&gt; word[:4] + word[4:]
'Python'
</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 data-language="python"> +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
</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 data-language="python">&gt;&gt;&gt; word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
IndexError: string index out of range
</pre> <p>However, out of range slice indexes are handled gracefully when used for slicing:</p> <pre data-language="python">&gt;&gt;&gt; word[4:42]
'on'
&gt;&gt;&gt; word[42:]
''
</pre> <p>Python strings cannot be changed — they are <a class="reference internal" href="../glossary#term-immutable"><span class="xref std std-term">immutable</span></a>. Therefore, assigning to an indexed position in the string results in an error:</p> <pre data-language="python">&gt;&gt;&gt; word[0] = 'J'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'str' object does not support item assignment
&gt;&gt;&gt; word[2:] = 'py'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'str' object does not support item assignment
</pre> <p>If you need a different string, you should create a new one:</p> <pre data-language="python">&gt;&gt;&gt; 'J' + word[1:]
'Jython'
&gt;&gt;&gt; word[:2] + 'py'
'Pypy'
</pre> <p>The built-in function <a class="reference internal" href="../library/functions#len" title="len"><code>len()</code></a> returns the length of a string:</p> <pre data-language="python">&gt;&gt;&gt; s = 'supercalifragilisticexpialidocious'
&gt;&gt;&gt; len(s)
34
</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference internal" href="../library/stdtypes#textseq"><span class="std std-ref">Text Sequence Type — str</span></a></dt>
<dd>
<p>Strings are examples of <em>sequence types</em>, and support the common operations supported by such types.</p> </dd> <dt><a class="reference internal" href="../library/stdtypes#string-methods"><span class="std std-ref">String Methods</span></a></dt>
<dd>
<p>Strings support a large number of methods for basic transformations and searching.</p> </dd> <dt><a class="reference internal" href="../reference/lexical_analysis#f-strings"><span class="std std-ref">f-strings</span></a></dt>
<dd>
<p>String literals that have embedded expressions.</p> </dd> <dt><a class="reference internal" href="../library/string#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt>
<dd>
<p>Information about string formatting with <a class="reference internal" href="../library/stdtypes#str.format" title="str.format"><code>str.format()</code></a>.</p> </dd> <dt><a class="reference internal" href="../library/stdtypes#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a></dt>
<dd>
<p>The old formatting operations invoked when strings are the left operand of the <code>%</code> operator are described in more detail here.</p> </dd> </dl> </div> </section> <section id="lists"> <span id="tut-lists"></span><h3>
<span class="section-number">3.1.3. </span>Lists</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 data-language="python">&gt;&gt;&gt; squares = [1, 4, 9, 16, 25]
&gt;&gt;&gt; squares
[1, 4, 9, 16, 25]
</pre> <p>Like strings (and all other built-in <a class="reference internal" href="../glossary#term-sequence"><span class="xref std std-term">sequence</span></a> types), lists can be indexed and sliced:</p> <pre data-language="python">&gt;&gt;&gt; squares[0]  # indexing returns the item
1
&gt;&gt;&gt; squares[-1]
25
&gt;&gt;&gt; squares[-3:]  # slicing returns a new list
[9, 16, 25]
</pre> <p>All slice operations return a new list containing the requested elements. This means that the following slice returns a <a class="reference internal" href="../library/copy#shallow-vs-deep-copy"><span class="std std-ref">shallow copy</span></a> of the list:</p> <pre data-language="python">&gt;&gt;&gt; squares[:]
[1, 4, 9, 16, 25]
</pre> <p>Lists also support operations like concatenation:</p> <pre data-language="python">&gt;&gt;&gt; squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
</pre> <p>Unlike strings, which are <a class="reference internal" href="../glossary#term-immutable"><span class="xref std std-term">immutable</span></a>, lists are a <a class="reference internal" href="../glossary#term-mutable"><span class="xref std std-term">mutable</span></a> type, i.e. it is possible to change their content:</p> <pre data-language="python">&gt;&gt;&gt; cubes = [1, 8, 27, 65, 125]  # something's wrong here
&gt;&gt;&gt; 4 ** 3  # the cube of 4 is 64, not 65!
64
&gt;&gt;&gt; cubes[3] = 64  # replace the wrong value
&gt;&gt;&gt; cubes
[1, 8, 27, 64, 125]
</pre> <p>You can also add new items at the end of the list, by using the <code>list.append()</code> <em>method</em> (we will see more about methods later):</p> <pre data-language="python">&gt;&gt;&gt; cubes.append(216)  # add the cube of 6
&gt;&gt;&gt; cubes.append(7 ** 3)  # and the cube of 7
&gt;&gt;&gt; cubes
[1, 8, 27, 64, 125, 216, 343]
</pre> <p>Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:</p> <pre data-language="python">&gt;&gt;&gt; letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
&gt;&gt;&gt; letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
&gt;&gt;&gt; # replace some values
&gt;&gt;&gt; letters[2:5] = ['C', 'D', 'E']
&gt;&gt;&gt; letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
&gt;&gt;&gt; # now remove them
&gt;&gt;&gt; letters[2:5] = []
&gt;&gt;&gt; letters
['a', 'b', 'f', 'g']
&gt;&gt;&gt; # clear the list by replacing all the elements with an empty list
&gt;&gt;&gt; letters[:] = []
&gt;&gt;&gt; letters
[]
</pre> <p>The built-in function <a class="reference internal" href="../library/functions#len" title="len"><code>len()</code></a> also applies to lists:</p> <pre data-language="python">&gt;&gt;&gt; letters = ['a', 'b', 'c', 'd']
&gt;&gt;&gt; len(letters)
4
</pre> <p>It is possible to nest lists (create lists containing other lists), for example:</p> <pre data-language="python">&gt;&gt;&gt; a = ['a', 'b', 'c']
&gt;&gt;&gt; n = [1, 2, 3]
&gt;&gt;&gt; x = [a, n]
&gt;&gt;&gt; x
[['a', 'b', 'c'], [1, 2, 3]]
&gt;&gt;&gt; x[0]
['a', 'b', 'c']
&gt;&gt;&gt; x[0][1]
'b'
</pre> </section> </section> <section id="first-steps-towards-programming"> <span id="tut-firststeps"></span><h2>
<span class="section-number">3.2. </span>First Steps Towards Programming</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 class="reference external" href="https://en.wikipedia.org/wiki/Fibonacci_sequence">Fibonacci series</a> as follows:</p> <pre data-language="python">&gt;&gt;&gt; # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
&gt;&gt;&gt; while a &lt; 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8
</pre> <p>This example introduces several new features.</p> <ul> <li>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.</li> <li>The <a class="reference internal" href="../reference/compound_stmts#while"><code>while</code></a> loop executes as long as the condition (here: <code>a &lt; 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>&lt;</code> (less than), <code>&gt;</code> (greater than), <code>==</code> (equal to), <code>&lt;=</code> (less than or equal to), <code>&gt;=</code> (greater than or equal to) and <code>!=</code> (not equal to).</li> <li>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.</li> <li>
<p>The <a class="reference internal" href="../library/functions#print" title="print"><code>print()</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 data-language="python">&gt;&gt;&gt; i = 256*256
&gt;&gt;&gt; print('The value of i is', i)
The value of i is 65536
</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 data-language="python">&gt;&gt;&gt; a, b = 0, 1
&gt;&gt;&gt; while a &lt; 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,
</pre> </li> </ul> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id3">
<code>1</code> </dt> <dd>
<p>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> </dd> <dt class="label" id="id4">
<code>2</code> </dt> <dd>
<p>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> </dd> </dl> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/tutorial/introduction.html" class="_attribution-link">https://docs.python.org/3.12/tutorial/introduction.html</a>
  </p>
</div>