blob: e68c9b10d03e60b2a9c5a99dfbc4e824947acf08 [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
Georg Brandl116aa622007-08-15 14:28:22 +000014Many of the examples in this manual, even those entered at the interactive
15prompt, include comments. Comments in Python start with the hash character,
Georg Brandl5d955ed2008-09-13 17:18:21 +000016``#``, and extend to the end of the physical line. A comment may appear at the
17start of a line or following whitespace or code, but not within a string
Christian Heimes5b5e81c2007-12-31 16:14:33 +000018literal. A hash character within a string literal is just a hash character.
Georg Brandl5d955ed2008-09-13 17:18:21 +000019Since comments are to clarify code and are not interpreted by Python, they may
20be omitted when typing in examples.
Georg Brandl116aa622007-08-15 14:28:22 +000021
22Some examples::
23
24 # this is the first comment
Ezio Melotti86aecc32013-05-20 08:12:32 +030025 spam = 1 # and this is the second comment
26 # ... and now a third!
27 text = "# This is not a comment because it's inside quotes."
Georg Brandl116aa622007-08-15 14:28:22 +000028
29
30.. _tut-calculator:
31
32Using Python as a Calculator
33============================
34
35Let's try some simple Python commands. Start the interpreter and wait for the
36primary prompt, ``>>>``. (It shouldn't take long.)
37
38
39.. _tut-numbers:
40
41Numbers
42-------
43
44The interpreter acts as a simple calculator: you can type an expression at it
45and it will write the value. Expression syntax is straightforward: the
46operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
Ezio Melotti86aecc32013-05-20 08:12:32 +030047(for example, Pascal or C); parentheses (``()``) can be used for grouping.
48For example::
Georg Brandl116aa622007-08-15 14:28:22 +000049
Ezio Melotti86aecc32013-05-20 08:12:32 +030050 >>> 2 + 2
Georg Brandl116aa622007-08-15 14:28:22 +000051 4
Ezio Melotti86aecc32013-05-20 08:12:32 +030052 >>> 50 - 5*6
53 20
54 >>> (50 - 5*6) / 4
Guido van Rossum0616b792007-08-31 03:25:11 +000055 5.0
Ezio Melotti86aecc32013-05-20 08:12:32 +030056 >>> 8 / 5 # division always returns a floating point number
Mark Dickinson5a55b612009-06-28 20:59:42 +000057 1.6
Guido van Rossum0616b792007-08-31 03:25:11 +000058
Ezio Melotti86aecc32013-05-20 08:12:32 +030059The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
60the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type
Zachary Ware26d5fab2014-01-14 08:44:49 -060061:class:`float`. We will see more about numeric types later in the tutorial.
Guido van Rossum0616b792007-08-31 03:25:11 +000062
Ezio Melotti86aecc32013-05-20 08:12:32 +030063Division (``/``) always returns a float. To do :term:`floor division` and
64get an integer result (discarding any fractional result) you can use the ``//``
65operator; to calculate the remainder you can use ``%``::
Georg Brandl48310cd2009-01-03 21:18:54 +000066
Ezio Melotti86aecc32013-05-20 08:12:32 +030067 >>> 17 / 3 # classic division returns a float
68 5.666666666666667
69 >>>
70 >>> 17 // 3 # floor division discards the fractional part
71 5
72 >>> 17 % 3 # the % operator returns the remainder of the division
Georg Brandl116aa622007-08-15 14:28:22 +000073 2
Ezio Melotti86aecc32013-05-20 08:12:32 +030074 >>> 5 * 3 + 2 # result * divisor + remainder
75 17
Georg Brandl116aa622007-08-15 14:28:22 +000076
Zachary Ware2d1303672014-01-14 08:40:53 -060077With Python, it is possible to use the ``**`` operator to calculate powers [#]_::
Ezio Melotti86aecc32013-05-20 08:12:32 +030078
79 >>> 5 ** 2 # 5 squared
80 25
81 >>> 2 ** 7 # 2 to the power of 7
82 128
83
84The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
Georg Brandl116aa622007-08-15 14:28:22 +000085result is displayed before the next interactive prompt::
86
87 >>> width = 20
Ezio Melotti86aecc32013-05-20 08:12:32 +030088 >>> height = 5 * 9
Georg Brandl116aa622007-08-15 14:28:22 +000089 >>> width * height
90 900
91
Ezio Melotti86aecc32013-05-20 08:12:32 +030092If a variable is not "defined" (assigned a value), trying to use it will
93give you an error::
Georg Brandl5d955ed2008-09-13 17:18:21 +000094
Chris Jerdonek9bb56a62012-09-24 19:28:59 -070095 >>> n # try to access an undefined variable
Georg Brandl48310cd2009-01-03 21:18:54 +000096 Traceback (most recent call last):
Georg Brandl5d955ed2008-09-13 17:18:21 +000097 File "<stdin>", line 1, in <module>
98 NameError: name 'n' is not defined
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100There is full support for floating point; operators with mixed type operands
101convert the integer operand to floating point::
102
gfyounge405d4b2017-05-29 17:26:31 -0400103 >>> 4 * 3.75 - 1
104 14.0
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Georg Brandl116aa622007-08-15 14:28:22 +0000106In interactive mode, the last printed expression is assigned to the variable
107``_``. This means that when you are using Python as a desk calculator, it is
108somewhat easier to continue calculations, for example::
109
110 >>> tax = 12.5 / 100
111 >>> price = 100.50
112 >>> price * tax
113 12.5625
114 >>> price + _
115 113.0625
116 >>> round(_, 2)
117 113.06
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119This variable should be treated as read-only by the user. Don't explicitly
120assign a value to it --- you would create an independent local variable with the
121same name masking the built-in variable with its magic behavior.
122
Ezio Melotti86aecc32013-05-20 08:12:32 +0300123In addition to :class:`int` and :class:`float`, Python supports other types of
124numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
125Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
126and uses the ``j`` or ``J`` suffix to indicate the imaginary part
127(e.g. ``3+5j``).
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130.. _tut-strings:
131
132Strings
133-------
134
Ezio Melotti86aecc32013-05-20 08:12:32 +0300135Besides numbers, Python can also manipulate strings, which can be expressed
136in several ways. They can be enclosed in single quotes (``'...'``) or
137double quotes (``"..."``) with the same result [#]_. ``\`` can be used
138to escape quotes::
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Ezio Melotti86aecc32013-05-20 08:12:32 +0300140 >>> 'spam eggs' # single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000141 'spam eggs'
Ezio Melotti86aecc32013-05-20 08:12:32 +0300142 >>> 'doesn\'t' # use \' to escape the single quote...
Georg Brandl116aa622007-08-15 14:28:22 +0000143 "doesn't"
Ezio Melotti86aecc32013-05-20 08:12:32 +0300144 >>> "doesn't" # ...or use double quotes instead
Georg Brandl116aa622007-08-15 14:28:22 +0000145 "doesn't"
Andrés Delfino50924392018-06-18 01:34:30 -0300146 >>> '"Yes," they said.'
147 '"Yes," they said.'
148 >>> "\"Yes,\" they said."
149 '"Yes," they said.'
150 >>> '"Isn\'t," they said.'
151 '"Isn\'t," they said.'
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Ezio Melotti86aecc32013-05-20 08:12:32 +0300153In the interactive interpreter, the output string is enclosed in quotes and
154special characters are escaped with backslashes. While this might sometimes
155look different from the input (the enclosing quotes could change), the two
156strings are equivalent. The string is enclosed in double quotes if
157the string contains a single quote and no double quotes, otherwise it is
158enclosed in single quotes. The :func:`print` function produces a more
159readable output, by omitting the enclosing quotes and by printing escaped
160and special characters::
Guido van Rossum0616b792007-08-31 03:25:11 +0000161
Andrés Delfino50924392018-06-18 01:34:30 -0300162 >>> '"Isn\'t," they said.'
163 '"Isn\'t," they said.'
164 >>> print('"Isn\'t," they said.')
165 "Isn't," they said.
Ezio Melotti86aecc32013-05-20 08:12:32 +0300166 >>> s = 'First line.\nSecond line.' # \n means newline
167 >>> s # without print(), \n is included in the output
168 'First line.\nSecond line.'
169 >>> print(s) # with print(), \n produces a new line
170 First line.
171 Second line.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Ezio Melotti86aecc32013-05-20 08:12:32 +0300173If you don't want characters prefaced by ``\`` to be interpreted as
174special characters, you can use *raw strings* by adding an ``r`` before
175the first quote::
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Ezio Melotti86aecc32013-05-20 08:12:32 +0300177 >>> print('C:\some\name') # here \n means newline!
178 C:\some
179 ame
180 >>> print(r'C:\some\name') # note the r before the quote
181 C:\some\name
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Ezio Melotti86aecc32013-05-20 08:12:32 +0300183String literals can span multiple lines. One way is using triple-quotes:
184``"""..."""`` or ``'''...'''``. End of lines are automatically
185included in the string, but it's possible to prevent this by adding a ``\`` at
186the end of the line. The following example::
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000187
Terry Reedy02a807e2010-11-12 04:22:22 +0000188 print("""\
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000189 Usage: thingy [OPTIONS]
190 -h Display this usage message
191 -H hostname Hostname to connect to
Ezio Melottib297e712009-09-25 20:14:02 +0000192 """)
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000193
Ezio Melotti86aecc32013-05-20 08:12:32 +0300194produces the following output (note that the initial newline is not included):
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000195
196.. code-block:: text
197
198 Usage: thingy [OPTIONS]
199 -h Display this usage message
200 -H hostname Hostname to connect to
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202Strings can be concatenated (glued together) with the ``+`` operator, and
203repeated with ``*``::
204
Ezio Melotti86aecc32013-05-20 08:12:32 +0300205 >>> # 3 times 'un', followed by 'ium'
206 >>> 3 * 'un' + 'ium'
207 'unununium'
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Ezio Melotti86aecc32013-05-20 08:12:32 +0300209Two or more *string literals* (i.e. the ones enclosed between quotes) next
210to each other are automatically concatenated. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Ezio Melotti86aecc32013-05-20 08:12:32 +0300212 >>> 'Py' 'thon'
213 'Python'
214
Will White78a57222017-11-24 17:28:12 +0000215This feature is particularly useful when you want to break long strings::
216
217 >>> text = ('Put several strings within parentheses '
218 ... 'to have them joined together.')
219 >>> text
220 'Put several strings within parentheses to have them joined together.'
221
Ezio Melotti86aecc32013-05-20 08:12:32 +0300222This only works with two literals though, not with variables or expressions::
223
224 >>> prefix = 'Py'
225 >>> prefix 'thon' # can't concatenate a variable and a string literal
Lew Kurtzf0195792018-09-10 18:13:08 -0700226 File "<stdin>", line 1
227 prefix 'thon'
228 ^
Ezio Melotti86aecc32013-05-20 08:12:32 +0300229 SyntaxError: invalid syntax
230 >>> ('un' * 3) 'ium'
Lew Kurtzf0195792018-09-10 18:13:08 -0700231 File "<stdin>", line 1
232 ('un' * 3) 'ium'
233 ^
Georg Brandl116aa622007-08-15 14:28:22 +0000234 SyntaxError: invalid syntax
235
Ezio Melotti86aecc32013-05-20 08:12:32 +0300236If you want to concatenate variables or a variable and a literal, use ``+``::
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Ezio Melotti86aecc32013-05-20 08:12:32 +0300238 >>> prefix + 'thon'
239 'Python'
240
Ezio Melotti86aecc32013-05-20 08:12:32 +0300241Strings can be *indexed* (subscripted), with the first character having index 0.
242There is no separate character type; a character is simply a string of size
243one::
244
245 >>> word = 'Python'
246 >>> word[0] # character in position 0
247 'P'
248 >>> word[5] # character in position 5
249 'n'
250
251Indices may also be negative numbers, to start counting from the right::
252
253 >>> word[-1] # last character
254 'n'
255 >>> word[-2] # second-last character
256 'o'
257 >>> word[-6]
258 'P'
259
260Note that since -0 is the same as 0, negative indices start from -1.
261
262In addition to indexing, *slicing* is also supported. While indexing is used
263to obtain individual characters, *slicing* allows you to obtain substring::
264
265 >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
266 'Py'
Ezio Melotti93dd6932013-07-08 17:52:54 +0200267 >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
Ezio Melotti86aecc32013-05-20 08:12:32 +0300268 'tho'
269
270Note how the start is always included, and the end always excluded. This
271makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
272
273 >>> word[:2] + word[2:]
274 'Python'
275 >>> word[:4] + word[4:]
276 'Python'
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278Slice indices have useful defaults; an omitted first index defaults to zero, an
279omitted second index defaults to the size of the string being sliced. ::
280
Serhiy Storchakadba90392016-05-10 12:01:23 +0300281 >>> word[:2] # character from the beginning to position 2 (excluded)
Ezio Melotti86aecc32013-05-20 08:12:32 +0300282 'Py'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300283 >>> word[4:] # characters from position 4 (included) to the end
Ezio Melotti86aecc32013-05-20 08:12:32 +0300284 'on'
Serhiy Storchakadba90392016-05-10 12:01:23 +0300285 >>> word[-2:] # characters from the second-last (included) to the end
Ezio Melotti86aecc32013-05-20 08:12:32 +0300286 'on'
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288One way to remember how slices work is to think of the indices as pointing
289*between* characters, with the left edge of the first character numbered 0.
290Then the right edge of the last character of a string of *n* characters has
291index *n*, for example::
292
Ezio Melotti86aecc32013-05-20 08:12:32 +0300293 +---+---+---+---+---+---+
294 | P | y | t | h | o | n |
295 +---+---+---+---+---+---+
296 0 1 2 3 4 5 6
297 -6 -5 -4 -3 -2 -1
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Ezio Melotti86aecc32013-05-20 08:12:32 +0300299The first row of numbers gives the position of the indices 0...6 in the string;
Georg Brandl116aa622007-08-15 14:28:22 +0000300the second row gives the corresponding negative indices. The slice from *i* to
301*j* consists of all characters between the edges labeled *i* and *j*,
302respectively.
303
304For non-negative indices, the length of a slice is the difference of the
305indices, if both are within bounds. For example, the length of ``word[1:3]`` is
3062.
307
Martin Panter7462b6492015-11-02 03:37:02 +0000308Attempting to use an index that is too large will result in an error::
Ezio Melotti86aecc32013-05-20 08:12:32 +0300309
Berker Peksag23381562014-12-17 14:56:47 +0200310 >>> word[42] # the word only has 6 characters
Ezio Melotti86aecc32013-05-20 08:12:32 +0300311 Traceback (most recent call last):
312 File "<stdin>", line 1, in <module>
313 IndexError: string index out of range
314
315However, out of range slice indexes are handled gracefully when used for
316slicing::
317
318 >>> word[4:42]
319 'on'
320 >>> word[42:]
321 ''
322
323Python strings cannot be changed --- they are :term:`immutable`.
324Therefore, assigning to an indexed position in the string results in an error::
325
326 >>> word[0] = 'J'
Lew Kurtzf0195792018-09-10 18:13:08 -0700327 Traceback (most recent call last):
328 File "<stdin>", line 1, in <module>
Ezio Melotti86aecc32013-05-20 08:12:32 +0300329 TypeError: 'str' object does not support item assignment
330 >>> word[2:] = 'py'
Lew Kurtzf0195792018-09-10 18:13:08 -0700331 Traceback (most recent call last):
332 File "<stdin>", line 1, in <module>
Ezio Melotti86aecc32013-05-20 08:12:32 +0300333 TypeError: 'str' object does not support item assignment
334
335If you need a different string, you should create a new one::
336
337 >>> 'J' + word[1:]
338 'Jython'
339 >>> word[:2] + 'py'
340 'Pypy'
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342The built-in function :func:`len` returns the length of a string::
343
344 >>> s = 'supercalifragilisticexpialidocious'
345 >>> len(s)
346 34
347
348
349.. seealso::
350
Ezio Melottia6229e62012-10-12 10:59:14 +0300351 :ref:`textseq`
Georg Brandl48310cd2009-01-03 21:18:54 +0000352 Strings are examples of *sequence types*, and support the common
Guido van Rossum0616b792007-08-31 03:25:11 +0000353 operations supported by such types.
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 :ref:`string-methods`
Guido van Rossum0616b792007-08-31 03:25:11 +0000356 Strings support a large number of methods for
Georg Brandl116aa622007-08-15 14:28:22 +0000357 basic transformations and searching.
358
Martin Panterbc1ee462016-02-13 00:41:37 +0000359 :ref:`f-strings`
360 String literals that have embedded expressions.
361
Martin Panterd5db1472016-02-08 01:34:09 +0000362 :ref:`formatstrings`
363 Information about string formatting with :meth:`str.format`.
Benjamin Petersone6f00632008-05-26 01:03:56 +0000364
365 :ref:`old-string-formatting`
Jim Fasarakis-Hilliard53c18922017-02-25 23:13:33 +0200366 The old formatting operations invoked when strings are
Benjamin Petersone6f00632008-05-26 01:03:56 +0000367 the left operand of the ``%`` operator are described in more detail here.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369
Georg Brandl116aa622007-08-15 14:28:22 +0000370.. _tut-lists:
371
372Lists
373-----
374
375Python knows a number of *compound* data types, used to group together other
376values. The most versatile is the *list*, which can be written as a list of
Ezio Melotti86aecc32013-05-20 08:12:32 +0300377comma-separated values (items) between square brackets. Lists might contain
378items of different types, but usually the items all have the same type. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000379
Larry Hastings3732ed22014-03-15 21:13:56 -0700380 >>> squares = [1, 4, 9, 16, 25]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300381 >>> squares
Larry Hastings3732ed22014-03-15 21:13:56 -0700382 [1, 4, 9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Ezio Melotti86aecc32013-05-20 08:12:32 +0300384Like strings (and all other built-in :term:`sequence` type), lists can be
385indexed and sliced::
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Ezio Melotti86aecc32013-05-20 08:12:32 +0300387 >>> squares[0] # indexing returns the item
388 1
389 >>> squares[-1]
390 25
391 >>> squares[-3:] # slicing returns a new list
392 [9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Benjamin Peterson886af962010-03-21 23:13:07 +0000394All slice operations return a new list containing the requested elements. This
Ezio Melotti86aecc32013-05-20 08:12:32 +0300395means that the following slice returns a new (shallow) copy of the list::
Benjamin Peterson886af962010-03-21 23:13:07 +0000396
Ezio Melotti86aecc32013-05-20 08:12:32 +0300397 >>> squares[:]
Larry Hastings3732ed22014-03-15 21:13:56 -0700398 [1, 4, 9, 16, 25]
Benjamin Peterson886af962010-03-21 23:13:07 +0000399
Berker Peksagb68c4202015-01-27 02:52:14 +0200400Lists also support operations like concatenation::
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Ezio Melotti86aecc32013-05-20 08:12:32 +0300402 >>> squares + [36, 49, 64, 81, 100]
Larry Hastings3732ed22014-03-15 21:13:56 -0700403 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300404
405Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
406type, i.e. it is possible to change their content::
407
408 >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
409 >>> 4 ** 3 # the cube of 4 is 64, not 65!
410 64
411 >>> cubes[3] = 64 # replace the wrong value
412 >>> cubes
413 [1, 8, 27, 64, 125]
414
415You can also add new items at the end of the list, by using
416the :meth:`~list.append` *method* (we will see more about methods later)::
417
418 >>> cubes.append(216) # add the cube of 6
419 >>> cubes.append(7 ** 3) # and the cube of 7
420 >>> cubes
421 [1, 8, 27, 64, 125, 216, 343]
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423Assignment to slices is also possible, and this can even change the size of the
424list or clear it entirely::
425
Ezio Melotti86aecc32013-05-20 08:12:32 +0300426 >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
427 >>> letters
428 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
429 >>> # replace some values
430 >>> letters[2:5] = ['C', 'D', 'E']
431 >>> letters
432 ['a', 'b', 'C', 'D', 'E', 'f', 'g']
433 >>> # now remove them
434 >>> letters[2:5] = []
435 >>> letters
436 ['a', 'b', 'f', 'g']
437 >>> # clear the list by replacing all the elements with an empty list
438 >>> letters[:] = []
439 >>> letters
Georg Brandl116aa622007-08-15 14:28:22 +0000440 []
441
442The built-in function :func:`len` also applies to lists::
443
Ezio Melotti86aecc32013-05-20 08:12:32 +0300444 >>> letters = ['a', 'b', 'c', 'd']
445 >>> len(letters)
Guido van Rossum58da9312007-11-10 23:39:45 +0000446 4
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448It is possible to nest lists (create lists containing other lists), for
449example::
450
Ezio Melotti86aecc32013-05-20 08:12:32 +0300451 >>> a = ['a', 'b', 'c']
452 >>> n = [1, 2, 3]
453 >>> x = [a, n]
454 >>> x
455 [['a', 'b', 'c'], [1, 2, 3]]
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300456 >>> x[0]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300457 ['a', 'b', 'c']
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300458 >>> x[0][1]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300459 'b'
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461.. _tut-firststeps:
462
463First Steps Towards Programming
464===============================
465
466Of course, we can use Python for more complicated tasks than adding two and two
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700467together. For instance, we can write an initial sub-sequence of the
468`Fibonacci series <https://en.wikipedia.org/wiki/Fibonacci_number>`_
469as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471 >>> # Fibonacci series:
472 ... # the sum of two elements defines the next
473 ... a, b = 0, 1
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700474 >>> while a < 10:
475 ... print(a)
Georg Brandl22ec03c2008-01-07 17:32:13 +0000476 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000477 ...
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700478 0
Georg Brandl116aa622007-08-15 14:28:22 +0000479 1
480 1
481 2
482 3
483 5
484 8
485
486This example introduces several new features.
487
488* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
489 simultaneously get the new values 0 and 1. On the last line this is used again,
490 demonstrating that the expressions on the right-hand side are all evaluated
491 first before any of the assignments take place. The right-hand side expressions
492 are evaluated from the left to the right.
493
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700494* The :keyword:`while` loop executes as long as the condition (here: ``a < 10``)
Georg Brandl116aa622007-08-15 14:28:22 +0000495 remains true. In Python, like in C, any non-zero integer value is true; zero is
496 false. The condition may also be a string or list value, in fact any sequence;
497 anything with a non-zero length is true, empty sequences are false. The test
498 used in the example is a simple comparison. The standard comparison operators
499 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
500 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
501 and ``!=`` (not equal to).
502
503* The *body* of the loop is *indented*: indentation is Python's way of grouping
Georg Brandl1532c8f2011-12-25 19:03:07 +0100504 statements. At the interactive prompt, you have to type a tab or space(s) for
505 each indented line. In practice you will prepare more complicated input
506 for Python with a text editor; all decent text editors have an auto-indent
507 facility. When a compound statement is entered interactively, it must be
508 followed by a blank line to indicate completion (since the parser cannot
509 guess when you have typed the last line). Note that each line within a basic
510 block must be indented by the same amount.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Benjamin Peterson07819002013-01-20 10:05:13 -0500512* The :func:`print` function writes the value of the argument(s) it is given.
513 It differs from just writing the expression you want to write (as we did
514 earlier in the calculator examples) in the way it handles multiple arguments,
515 floating point quantities, and strings. Strings are printed without quotes,
516 and a space is inserted between items, so you can format things nicely, like
517 this::
Georg Brandl116aa622007-08-15 14:28:22 +0000518
519 >>> i = 256*256
Guido van Rossum0616b792007-08-31 03:25:11 +0000520 >>> print('The value of i is', i)
Georg Brandl116aa622007-08-15 14:28:22 +0000521 The value of i is 65536
522
Benjamin Peterson648fa192013-01-20 10:09:44 -0500523 The keyword argument *end* can be used to avoid the newline after the output,
524 or end the output with a different string::
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526 >>> a, b = 0, 1
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700527 >>> while a < 1000:
528 ... print(a, end=',')
Georg Brandl116aa622007-08-15 14:28:22 +0000529 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000530 ...
Raymond Hettinger8c26a342017-10-14 07:36:08 -0700531 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Ezio Melotti86aecc32013-05-20 08:12:32 +0300532
533
534.. rubric:: Footnotes
535
536.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
537 interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this
538 and get ``9``, you can use ``(-3)**2``.
539
540.. [#] Unlike other languages, special characters such as ``\n`` have the
541 same meaning with both single (``'...'``) and double (``"..."``) quotes.
542 The only difference between the two is that within single quotes you don't
543 need to escape ``"`` (but you have to escape ``\'``) and vice versa.