blob: 3e0c99558ed7f3c9619fd476b8fe3fb989d5636f [file] [log] [blame]
Serhiy Storchaka410d77f2015-05-25 12:27:39 +03001.. _tut-informal:
Georg Brandl116aa622007-08-15 14:28:22 +00002
3**********************************
4An Informal Introduction to Python
5**********************************
6
7In the following examples, input and output are distinguished by the presence or
Ezio Melotti86aecc32013-05-20 08:12:32 +03008absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type
Georg Brandl116aa622007-08-15 14:28:22 +00009everything after the prompt, when the prompt appears; lines that do not begin
10with a prompt are output from the interpreter. Note that a secondary prompt on a
11line by itself in an example means you must type a blank line; this is used to
12end a multi-line command.
13
Serhiy Storchaka913876d2018-10-28 13:41:26 +020014.. index:: single: # (hash); comment
Serhiy Storchakaddb961d2018-10-26 09:00:49 +030015
Georg Brandl116aa622007-08-15 14:28:22 +000016Many of the examples in this manual, even those entered at the interactive
17prompt, include comments. Comments in Python start with the hash character,
Georg Brandl5d955ed2008-09-13 17:18:21 +000018``#``, and extend to the end of the physical line. A comment may appear at the
19start of a line or following whitespace or code, but not within a string
Christian Heimes5b5e81c2007-12-31 16:14:33 +000020literal. A hash character within a string literal is just a hash character.
Georg Brandl5d955ed2008-09-13 17:18:21 +000021Since comments are to clarify code and are not interpreted by Python, they may
22be omitted when typing in examples.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24Some examples::
25
26 # this is the first comment
Ezio Melotti86aecc32013-05-20 08:12:32 +030027 spam = 1 # and this is the second comment
28 # ... and now a third!
29 text = "# This is not a comment because it's inside quotes."
Georg Brandl116aa622007-08-15 14:28:22 +000030
31
32.. _tut-calculator:
33
34Using Python as a Calculator
35============================
36
37Let's try some simple Python commands. Start the interpreter and wait for the
38primary prompt, ``>>>``. (It shouldn't take long.)
39
40
41.. _tut-numbers:
42
43Numbers
44-------
45
46The interpreter acts as a simple calculator: you can type an expression at it
47and it will write the value. Expression syntax is straightforward: the
48operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
Ezio Melotti86aecc32013-05-20 08:12:32 +030049(for example, Pascal or C); parentheses (``()``) can be used for grouping.
50For example::
Georg Brandl116aa622007-08-15 14:28:22 +000051
Ezio Melotti86aecc32013-05-20 08:12:32 +030052 >>> 2 + 2
Georg Brandl116aa622007-08-15 14:28:22 +000053 4
Ezio Melotti86aecc32013-05-20 08:12:32 +030054 >>> 50 - 5*6
55 20
56 >>> (50 - 5*6) / 4
Guido van Rossum0616b792007-08-31 03:25:11 +000057 5.0
Ezio Melotti86aecc32013-05-20 08:12:32 +030058 >>> 8 / 5 # division always returns a floating point number
Mark Dickinson5a55b612009-06-28 20:59:42 +000059 1.6
Guido van Rossum0616b792007-08-31 03:25:11 +000060
Ezio Melotti86aecc32013-05-20 08:12:32 +030061The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
62the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type
Zachary Ware26d5fab2014-01-14 08:44:49 -060063:class:`float`. We will see more about numeric types later in the tutorial.
Guido van Rossum0616b792007-08-31 03:25:11 +000064
Ezio Melotti86aecc32013-05-20 08:12:32 +030065Division (``/``) always returns a float. To do :term:`floor division` and
66get an integer result (discarding any fractional result) you can use the ``//``
67operator; to calculate the remainder you can use ``%``::
Georg Brandl48310cd2009-01-03 21:18:54 +000068
Ezio Melotti86aecc32013-05-20 08:12:32 +030069 >>> 17 / 3 # classic division returns a float
70 5.666666666666667
71 >>>
72 >>> 17 // 3 # floor division discards the fractional part
73 5
74 >>> 17 % 3 # the % operator returns the remainder of the division
Georg Brandl116aa622007-08-15 14:28:22 +000075 2
Ezio Melotti86aecc32013-05-20 08:12:32 +030076 >>> 5 * 3 + 2 # result * divisor + remainder
77 17
Georg Brandl116aa622007-08-15 14:28:22 +000078
Zachary Ware2d1303672014-01-14 08:40:53 -060079With Python, it is possible to use the ``**`` operator to calculate powers [#]_::
Ezio Melotti86aecc32013-05-20 08:12:32 +030080
81 >>> 5 ** 2 # 5 squared
82 25
83 >>> 2 ** 7 # 2 to the power of 7
84 128
85
86The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
Georg Brandl116aa622007-08-15 14:28:22 +000087result is displayed before the next interactive prompt::
88
89 >>> width = 20
Ezio Melotti86aecc32013-05-20 08:12:32 +030090 >>> height = 5 * 9
Georg Brandl116aa622007-08-15 14:28:22 +000091 >>> width * height
92 900
93
Ezio Melotti86aecc32013-05-20 08:12:32 +030094If a variable is not "defined" (assigned a value), trying to use it will
95give you an error::
Georg Brandl5d955ed2008-09-13 17:18:21 +000096
Chris Jerdonek9bb56a62012-09-24 19:28:59 -070097 >>> n # try to access an undefined variable
Georg Brandl48310cd2009-01-03 21:18:54 +000098 Traceback (most recent call last):
Georg Brandl5d955ed2008-09-13 17:18:21 +000099 File "<stdin>", line 1, in <module>
100 NameError: name 'n' is not defined
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102There is full support for floating point; operators with mixed type operands
103convert the integer operand to floating point::
104
gfyounge405d4b2017-05-29 17:26:31 -0400105 >>> 4 * 3.75 - 1
106 14.0
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Georg Brandl116aa622007-08-15 14:28:22 +0000108In interactive mode, the last printed expression is assigned to the variable
109``_``. This means that when you are using Python as a desk calculator, it is
110somewhat easier to continue calculations, for example::
111
112 >>> tax = 12.5 / 100
113 >>> price = 100.50
114 >>> price * tax
115 12.5625
116 >>> price + _
117 113.0625
118 >>> round(_, 2)
119 113.06
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121This variable should be treated as read-only by the user. Don't explicitly
122assign a value to it --- you would create an independent local variable with the
123same name masking the built-in variable with its magic behavior.
124
Ezio Melotti86aecc32013-05-20 08:12:32 +0300125In addition to :class:`int` and :class:`float`, Python supports other types of
126numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
127Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
128and uses the ``j`` or ``J`` suffix to indicate the imaginary part
129(e.g. ``3+5j``).
130
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132.. _tut-strings:
133
134Strings
135-------
136
Ezio Melotti86aecc32013-05-20 08:12:32 +0300137Besides numbers, Python can also manipulate strings, which can be expressed
138in several ways. They can be enclosed in single quotes (``'...'``) or
139double quotes (``"..."``) with the same result [#]_. ``\`` can be used
140to escape quotes::
Georg Brandl116aa622007-08-15 14:28:22 +0000141
Ezio Melotti86aecc32013-05-20 08:12:32 +0300142 >>> 'spam eggs' # single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000143 'spam eggs'
Ezio Melotti86aecc32013-05-20 08:12:32 +0300144 >>> 'doesn\'t' # use \' to escape the single quote...
Georg Brandl116aa622007-08-15 14:28:22 +0000145 "doesn't"
Ezio Melotti86aecc32013-05-20 08:12:32 +0300146 >>> "doesn't" # ...or use double quotes instead
Georg Brandl116aa622007-08-15 14:28:22 +0000147 "doesn't"
Andrés Delfino50924392018-06-18 01:34:30 -0300148 >>> '"Yes," they said.'
149 '"Yes," they said.'
150 >>> "\"Yes,\" they said."
151 '"Yes," they said.'
152 >>> '"Isn\'t," they said.'
153 '"Isn\'t," they said.'
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Ezio Melotti86aecc32013-05-20 08:12:32 +0300155In the interactive interpreter, the output string is enclosed in quotes and
156special characters are escaped with backslashes. While this might sometimes
157look different from the input (the enclosing quotes could change), the two
158strings are equivalent. The string is enclosed in double quotes if
159the string contains a single quote and no double quotes, otherwise it is
160enclosed in single quotes. The :func:`print` function produces a more
161readable output, by omitting the enclosing quotes and by printing escaped
162and special characters::
Guido van Rossum0616b792007-08-31 03:25:11 +0000163
Andrés Delfino50924392018-06-18 01:34:30 -0300164 >>> '"Isn\'t," they said.'
165 '"Isn\'t," they said.'
166 >>> print('"Isn\'t," they said.')
167 "Isn't," they said.
Ezio Melotti86aecc32013-05-20 08:12:32 +0300168 >>> s = 'First line.\nSecond line.' # \n means newline
169 >>> s # without print(), \n is included in the output
170 'First line.\nSecond line.'
171 >>> print(s) # with print(), \n produces a new line
172 First line.
173 Second line.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
Ezio Melotti86aecc32013-05-20 08:12:32 +0300175If you don't want characters prefaced by ``\`` to be interpreted as
176special characters, you can use *raw strings* by adding an ``r`` before
177the first quote::
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Ezio Melotti86aecc32013-05-20 08:12:32 +0300179 >>> print('C:\some\name') # here \n means newline!
180 C:\some
181 ame
182 >>> print(r'C:\some\name') # note the r before the quote
183 C:\some\name
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Ezio Melotti86aecc32013-05-20 08:12:32 +0300185String literals can span multiple lines. One way is using triple-quotes:
186``"""..."""`` or ``'''...'''``. End of lines are automatically
187included in the string, but it's possible to prevent this by adding a ``\`` at
188the end of the line. The following example::
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000189
Terry Reedy02a807e2010-11-12 04:22:22 +0000190 print("""\
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000191 Usage: thingy [OPTIONS]
192 -h Display this usage message
193 -H hostname Hostname to connect to
Ezio Melottib297e712009-09-25 20:14:02 +0000194 """)
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000195
Ezio Melotti86aecc32013-05-20 08:12:32 +0300196produces the following output (note that the initial newline is not included):
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000197
198.. code-block:: text
199
200 Usage: thingy [OPTIONS]
201 -h Display this usage message
202 -H hostname Hostname to connect to
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204Strings can be concatenated (glued together) with the ``+`` operator, and
205repeated with ``*``::
206
Ezio Melotti86aecc32013-05-20 08:12:32 +0300207 >>> # 3 times 'un', followed by 'ium'
208 >>> 3 * 'un' + 'ium'
209 'unununium'
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Ezio Melotti86aecc32013-05-20 08:12:32 +0300211Two or more *string literals* (i.e. the ones enclosed between quotes) next
212to each other are automatically concatenated. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000213
Ezio Melotti86aecc32013-05-20 08:12:32 +0300214 >>> 'Py' 'thon'
215 'Python'
216
Will White78a57222017-11-24 17:28:12 +0000217This feature is particularly useful when you want to break long strings::
218
219 >>> text = ('Put several strings within parentheses '
220 ... 'to have them joined together.')
221 >>> text
222 'Put several strings within parentheses to have them joined together.'
223
Ezio Melotti86aecc32013-05-20 08:12:32 +0300224This only works with two literals though, not with variables or expressions::
225
226 >>> prefix = 'Py'
227 >>> prefix 'thon' # can't concatenate a variable and a string literal
Lew Kurtzf0195792018-09-10 18:13:08 -0700228 File "<stdin>", line 1
229 prefix 'thon'
230 ^
Ezio Melotti86aecc32013-05-20 08:12:32 +0300231 SyntaxError: invalid syntax
232 >>> ('un' * 3) 'ium'
Lew Kurtzf0195792018-09-10 18:13:08 -0700233 File "<stdin>", line 1
234 ('un' * 3) 'ium'
235 ^
Georg Brandl116aa622007-08-15 14:28:22 +0000236 SyntaxError: invalid syntax
237
Ezio Melotti86aecc32013-05-20 08:12:32 +0300238If you want to concatenate variables or a variable and a literal, use ``+``::
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Ezio Melotti86aecc32013-05-20 08:12:32 +0300240 >>> prefix + 'thon'
241 'Python'
242
Ezio Melotti86aecc32013-05-20 08:12:32 +0300243Strings can be *indexed* (subscripted), with the first character having index 0.
244There is no separate character type; a character is simply a string of size
245one::
246
247 >>> word = 'Python'
248 >>> word[0] # character in position 0
249 'P'
250 >>> word[5] # character in position 5
251 'n'
252
253Indices may also be negative numbers, to start counting from the right::
254
255 >>> word[-1] # last character
256 'n'
257 >>> word[-2] # second-last character
258 'o'
259 >>> word[-6]
260 'P'
261
262Note that since -0 is the same as 0, negative indices start from -1.
263
264In addition to indexing, *slicing* is also supported. While indexing is used
265to obtain individual characters, *slicing* allows you to obtain substring::
266
267 >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
268 'Py'
Ezio Melotti93dd6932013-07-08 17:52:54 +0200269 >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
Ezio Melotti86aecc32013-05-20 08:12:32 +0300270 'tho'
271
272Note how the start is always included, and the end always excluded. This
273makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
274
275 >>> word[:2] + word[2:]
276 'Python'
277 >>> word[:4] + word[4:]
278 'Python'
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280Slice indices have useful defaults; an omitted first index defaults to zero, an
281omitted second index defaults to the size of the string being sliced. ::
282
Serhiy Storchakadba90392016-05-10 12:01:23 +0300283 >>> word[:2] # character from the beginning to position 2 (excluded)
Ezio Melotti86aecc32013-05-20 08:12:32 +0300284 'Py'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300285 >>> word[4:] # characters from position 4 (included) to the end
Ezio Melotti86aecc32013-05-20 08:12:32 +0300286 'on'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300287 >>> word[-2:] # characters from the second-last (included) to the end
Ezio Melotti86aecc32013-05-20 08:12:32 +0300288 'on'
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290One way to remember how slices work is to think of the indices as pointing
291*between* characters, with the left edge of the first character numbered 0.
292Then the right edge of the last character of a string of *n* characters has
293index *n*, for example::
294
Ezio Melotti86aecc32013-05-20 08:12:32 +0300295 +---+---+---+---+---+---+
296 | P | y | t | h | o | n |
297 +---+---+---+---+---+---+
298 0 1 2 3 4 5 6
299 -6 -5 -4 -3 -2 -1
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Ezio Melotti86aecc32013-05-20 08:12:32 +0300301The first row of numbers gives the position of the indices 0...6 in the string;
Georg Brandl116aa622007-08-15 14:28:22 +0000302the second row gives the corresponding negative indices. The slice from *i* to
303*j* consists of all characters between the edges labeled *i* and *j*,
304respectively.
305
306For non-negative indices, the length of a slice is the difference of the
307indices, if both are within bounds. For example, the length of ``word[1:3]`` is
3082.
309
Martin Panter7462b6492015-11-02 03:37:02 +0000310Attempting to use an index that is too large will result in an error::
Ezio Melotti86aecc32013-05-20 08:12:32 +0300311
Berker Peksag23381562014-12-17 14:56:47 +0200312 >>> word[42] # the word only has 6 characters
Ezio Melotti86aecc32013-05-20 08:12:32 +0300313 Traceback (most recent call last):
314 File "<stdin>", line 1, in <module>
315 IndexError: string index out of range
316
317However, out of range slice indexes are handled gracefully when used for
318slicing::
319
320 >>> word[4:42]
321 'on'
322 >>> word[42:]
323 ''
324
325Python strings cannot be changed --- they are :term:`immutable`.
326Therefore, assigning to an indexed position in the string results in an error::
327
328 >>> word[0] = 'J'
Lew Kurtzf0195792018-09-10 18:13:08 -0700329 Traceback (most recent call last):
330 File "<stdin>", line 1, in <module>
Ezio Melotti86aecc32013-05-20 08:12:32 +0300331 TypeError: 'str' object does not support item assignment
332 >>> word[2:] = 'py'
Lew Kurtzf0195792018-09-10 18:13:08 -0700333 Traceback (most recent call last):
334 File "<stdin>", line 1, in <module>
Ezio Melotti86aecc32013-05-20 08:12:32 +0300335 TypeError: 'str' object does not support item assignment
336
337If you need a different string, you should create a new one::
338
339 >>> 'J' + word[1:]
340 'Jython'
341 >>> word[:2] + 'py'
342 'Pypy'
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344The built-in function :func:`len` returns the length of a string::
345
346 >>> s = 'supercalifragilisticexpialidocious'
347 >>> len(s)
348 34
349
350
351.. seealso::
352
Ezio Melottia6229e62012-10-12 10:59:14 +0300353 :ref:`textseq`
Georg Brandl48310cd2009-01-03 21:18:54 +0000354 Strings are examples of *sequence types*, and support the common
Guido van Rossum0616b792007-08-31 03:25:11 +0000355 operations supported by such types.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357 :ref:`string-methods`
Guido van Rossum0616b792007-08-31 03:25:11 +0000358 Strings support a large number of methods for
Georg Brandl116aa622007-08-15 14:28:22 +0000359 basic transformations and searching.
360
Martin Panterbc1ee462016-02-13 00:41:37 +0000361 :ref:`f-strings`
362 String literals that have embedded expressions.
363
Martin Panterd5db1472016-02-08 01:34:09 +0000364 :ref:`formatstrings`
365 Information about string formatting with :meth:`str.format`.
Benjamin Petersone6f00632008-05-26 01:03:56 +0000366
367 :ref:`old-string-formatting`
Jim Fasarakis-Hilliard53c18922017-02-25 23:13:33 +0200368 The old formatting operations invoked when strings are
Benjamin Petersone6f00632008-05-26 01:03:56 +0000369 the left operand of the ``%`` operator are described in more detail here.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371
Georg Brandl116aa622007-08-15 14:28:22 +0000372.. _tut-lists:
373
374Lists
375-----
376
377Python knows a number of *compound* data types, used to group together other
378values. The most versatile is the *list*, which can be written as a list of
Ezio Melotti86aecc32013-05-20 08:12:32 +0300379comma-separated values (items) between square brackets. Lists might contain
380items of different types, but usually the items all have the same type. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Larry Hastings3732ed22014-03-15 21:13:56 -0700382 >>> squares = [1, 4, 9, 16, 25]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300383 >>> squares
Larry Hastings3732ed22014-03-15 21:13:56 -0700384 [1, 4, 9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Ezio Melotti86aecc32013-05-20 08:12:32 +0300386Like strings (and all other built-in :term:`sequence` type), lists can be
387indexed and sliced::
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Ezio Melotti86aecc32013-05-20 08:12:32 +0300389 >>> squares[0] # indexing returns the item
390 1
391 >>> squares[-1]
392 25
393 >>> squares[-3:] # slicing returns a new list
394 [9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Benjamin Peterson886af962010-03-21 23:13:07 +0000396All slice operations return a new list containing the requested elements. This
Ezio Melotti86aecc32013-05-20 08:12:32 +0300397means that the following slice returns a new (shallow) copy of the list::
Benjamin Peterson886af962010-03-21 23:13:07 +0000398
Ezio Melotti86aecc32013-05-20 08:12:32 +0300399 >>> squares[:]
Larry Hastings3732ed22014-03-15 21:13:56 -0700400 [1, 4, 9, 16, 25]
Benjamin Peterson886af962010-03-21 23:13:07 +0000401
Berker Peksagb68c4202015-01-27 02:52:14 +0200402Lists also support operations like concatenation::
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Ezio Melotti86aecc32013-05-20 08:12:32 +0300404 >>> squares + [36, 49, 64, 81, 100]
Larry Hastings3732ed22014-03-15 21:13:56 -0700405 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300406
407Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
408type, i.e. it is possible to change their content::
409
410 >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
411 >>> 4 ** 3 # the cube of 4 is 64, not 65!
412 64
413 >>> cubes[3] = 64 # replace the wrong value
414 >>> cubes
415 [1, 8, 27, 64, 125]
416
417You can also add new items at the end of the list, by using
418the :meth:`~list.append` *method* (we will see more about methods later)::
419
420 >>> cubes.append(216) # add the cube of 6
421 >>> cubes.append(7 ** 3) # and the cube of 7
422 >>> cubes
423 [1, 8, 27, 64, 125, 216, 343]
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425Assignment to slices is also possible, and this can even change the size of the
426list or clear it entirely::
427
Ezio Melotti86aecc32013-05-20 08:12:32 +0300428 >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
429 >>> letters
430 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
431 >>> # replace some values
432 >>> letters[2:5] = ['C', 'D', 'E']
433 >>> letters
434 ['a', 'b', 'C', 'D', 'E', 'f', 'g']
435 >>> # now remove them
436 >>> letters[2:5] = []
437 >>> letters
438 ['a', 'b', 'f', 'g']
439 >>> # clear the list by replacing all the elements with an empty list
440 >>> letters[:] = []
441 >>> letters
Georg Brandl116aa622007-08-15 14:28:22 +0000442 []
443
444The built-in function :func:`len` also applies to lists::
445
Ezio Melotti86aecc32013-05-20 08:12:32 +0300446 >>> letters = ['a', 'b', 'c', 'd']
447 >>> len(letters)
Guido van Rossum58da9312007-11-10 23:39:45 +0000448 4
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450It is possible to nest lists (create lists containing other lists), for
451example::
452
Ezio Melotti86aecc32013-05-20 08:12:32 +0300453 >>> a = ['a', 'b', 'c']
454 >>> n = [1, 2, 3]
455 >>> x = [a, n]
456 >>> x
457 [['a', 'b', 'c'], [1, 2, 3]]
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300458 >>> x[0]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300459 ['a', 'b', 'c']
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300460 >>> x[0][1]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300461 'b'
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463.. _tut-firststeps:
464
465First Steps Towards Programming
466===============================
467
468Of course, we can use Python for more complicated tasks than adding two and two
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700469together. For instance, we can write an initial sub-sequence of the
470`Fibonacci series <https://en.wikipedia.org/wiki/Fibonacci_number>`_
471as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000472
473 >>> # Fibonacci series:
474 ... # the sum of two elements defines the next
475 ... a, b = 0, 1
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700476 >>> while a < 10:
477 ... print(a)
Georg Brandl22ec03c2008-01-07 17:32:13 +0000478 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000479 ...
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700480 0
Georg Brandl116aa622007-08-15 14:28:22 +0000481 1
482 1
483 2
484 3
485 5
486 8
487
488This example introduces several new features.
489
490* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
491 simultaneously get the new values 0 and 1. On the last line this is used again,
492 demonstrating that the expressions on the right-hand side are all evaluated
493 first before any of the assignments take place. The right-hand side expressions
494 are evaluated from the left to the right.
495
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700496* The :keyword:`while` loop executes as long as the condition (here: ``a < 10``)
Georg Brandl116aa622007-08-15 14:28:22 +0000497 remains true. In Python, like in C, any non-zero integer value is true; zero is
498 false. The condition may also be a string or list value, in fact any sequence;
499 anything with a non-zero length is true, empty sequences are false. The test
500 used in the example is a simple comparison. The standard comparison operators
501 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
502 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
503 and ``!=`` (not equal to).
504
505* The *body* of the loop is *indented*: indentation is Python's way of grouping
Georg Brandl1532c8f2011-12-25 19:03:07 +0100506 statements. At the interactive prompt, you have to type a tab or space(s) for
507 each indented line. In practice you will prepare more complicated input
508 for Python with a text editor; all decent text editors have an auto-indent
509 facility. When a compound statement is entered interactively, it must be
510 followed by a blank line to indicate completion (since the parser cannot
511 guess when you have typed the last line). Note that each line within a basic
512 block must be indented by the same amount.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
Benjamin Peterson07819002013-01-20 10:05:13 -0500514* The :func:`print` function writes the value of the argument(s) it is given.
515 It differs from just writing the expression you want to write (as we did
516 earlier in the calculator examples) in the way it handles multiple arguments,
517 floating point quantities, and strings. Strings are printed without quotes,
518 and a space is inserted between items, so you can format things nicely, like
519 this::
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521 >>> i = 256*256
Guido van Rossum0616b792007-08-31 03:25:11 +0000522 >>> print('The value of i is', i)
Georg Brandl116aa622007-08-15 14:28:22 +0000523 The value of i is 65536
524
Benjamin Peterson648fa192013-01-20 10:09:44 -0500525 The keyword argument *end* can be used to avoid the newline after the output,
526 or end the output with a different string::
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528 >>> a, b = 0, 1
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700529 >>> while a < 1000:
530 ... print(a, end=',')
Georg Brandl116aa622007-08-15 14:28:22 +0000531 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000532 ...
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700533 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Ezio Melotti86aecc32013-05-20 08:12:32 +0300534
535
536.. rubric:: Footnotes
537
538.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
539 interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this
540 and get ``9``, you can use ``(-3)**2``.
541
542.. [#] Unlike other languages, special characters such as ``\n`` have the
543 same meaning with both single (``'...'``) and double (``"..."``) quotes.
544 The only difference between the two is that within single quotes you don't
545 need to escape ``"`` (but you have to escape ``\'``) and vice versa.