blob: 9efd1ac8b073137112e14fb4a38e5f2483b66a80 [file] [log] [blame]
Terry Reedy02a807e2010-11-12 04:22:22 +00001.. _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
103 >>> 3 * 3.75 / 1.5
104 7.5
105 >>> 7.0 / 2
106 3.5
107
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"
148 >>> '"Yes," he said.'
149 '"Yes," he said.'
150 >>> "\"Yes,\" he said."
151 '"Yes," he said.'
152 >>> '"Isn\'t," she said.'
153 '"Isn\'t," she said.'
154
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
Ezio Melotti86aecc32013-05-20 08:12:32 +0300164 >>> '"Isn\'t," she said.'
165 '"Isn\'t," she said.'
166 >>> print('"Isn\'t," she said.')
167 "Isn't," she said.
168 >>> 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
217This only works with two literals though, not with variables or expressions::
218
219 >>> prefix = 'Py'
220 >>> prefix 'thon' # can't concatenate a variable and a string literal
221 ...
222 SyntaxError: invalid syntax
223 >>> ('un' * 3) 'ium'
224 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000225 SyntaxError: invalid syntax
226
Ezio Melotti86aecc32013-05-20 08:12:32 +0300227If you want to concatenate variables or a variable and a literal, use ``+``::
Georg Brandl116aa622007-08-15 14:28:22 +0000228
Ezio Melotti86aecc32013-05-20 08:12:32 +0300229 >>> prefix + 'thon'
230 'Python'
231
232This feature is particularly useful when you want to break long strings::
233
234 >>> text = ('Put several strings within parentheses '
235 'to have them joined together.')
236 >>> text
237 'Put several strings within parentheses to have them joined together.'
238
239Strings can be *indexed* (subscripted), with the first character having index 0.
240There is no separate character type; a character is simply a string of size
241one::
242
243 >>> word = 'Python'
244 >>> word[0] # character in position 0
245 'P'
246 >>> word[5] # character in position 5
247 'n'
248
249Indices may also be negative numbers, to start counting from the right::
250
251 >>> word[-1] # last character
252 'n'
253 >>> word[-2] # second-last character
254 'o'
255 >>> word[-6]
256 'P'
257
258Note that since -0 is the same as 0, negative indices start from -1.
259
260In addition to indexing, *slicing* is also supported. While indexing is used
261to obtain individual characters, *slicing* allows you to obtain substring::
262
263 >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
264 'Py'
Ezio Melotti93dd6932013-07-08 17:52:54 +0200265 >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
Ezio Melotti86aecc32013-05-20 08:12:32 +0300266 'tho'
267
268Note how the start is always included, and the end always excluded. This
269makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::
270
271 >>> word[:2] + word[2:]
272 'Python'
273 >>> word[:4] + word[4:]
274 'Python'
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276Slice indices have useful defaults; an omitted first index defaults to zero, an
277omitted second index defaults to the size of the string being sliced. ::
278
Ezio Melotti86aecc32013-05-20 08:12:32 +0300279 >>> word[:2] # character from the beginning to position 2 (excluded)
280 'Py'
281 >>> word[4:] # characters from position 4 (included) to the end
282 'on'
283 >>> word[-2:] # characters from the second-last (included) to the end
284 'on'
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286One way to remember how slices work is to think of the indices as pointing
287*between* characters, with the left edge of the first character numbered 0.
288Then the right edge of the last character of a string of *n* characters has
289index *n*, for example::
290
Ezio Melotti86aecc32013-05-20 08:12:32 +0300291 +---+---+---+---+---+---+
292 | P | y | t | h | o | n |
293 +---+---+---+---+---+---+
294 0 1 2 3 4 5 6
295 -6 -5 -4 -3 -2 -1
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Ezio Melotti86aecc32013-05-20 08:12:32 +0300297The first row of numbers gives the position of the indices 0...6 in the string;
Georg Brandl116aa622007-08-15 14:28:22 +0000298the second row gives the corresponding negative indices. The slice from *i* to
299*j* consists of all characters between the edges labeled *i* and *j*,
300respectively.
301
302For non-negative indices, the length of a slice is the difference of the
303indices, if both are within bounds. For example, the length of ``word[1:3]`` is
3042.
305
Ezio Melotti86aecc32013-05-20 08:12:32 +0300306Attempting to use a index that is too large will result in an error::
307
308 >>> word[42] # the word only has 7 characters
309 Traceback (most recent call last):
310 File "<stdin>", line 1, in <module>
311 IndexError: string index out of range
312
313However, out of range slice indexes are handled gracefully when used for
314slicing::
315
316 >>> word[4:42]
317 'on'
318 >>> word[42:]
319 ''
320
321Python strings cannot be changed --- they are :term:`immutable`.
322Therefore, assigning to an indexed position in the string results in an error::
323
324 >>> word[0] = 'J'
325 ...
326 TypeError: 'str' object does not support item assignment
327 >>> word[2:] = 'py'
328 ...
329 TypeError: 'str' object does not support item assignment
330
331If you need a different string, you should create a new one::
332
333 >>> 'J' + word[1:]
334 'Jython'
335 >>> word[:2] + 'py'
336 'Pypy'
337
Georg Brandl116aa622007-08-15 14:28:22 +0000338The built-in function :func:`len` returns the length of a string::
339
340 >>> s = 'supercalifragilisticexpialidocious'
341 >>> len(s)
342 34
343
344
345.. seealso::
346
Ezio Melottia6229e62012-10-12 10:59:14 +0300347 :ref:`textseq`
Georg Brandl48310cd2009-01-03 21:18:54 +0000348 Strings are examples of *sequence types*, and support the common
Guido van Rossum0616b792007-08-31 03:25:11 +0000349 operations supported by such types.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351 :ref:`string-methods`
Guido van Rossum0616b792007-08-31 03:25:11 +0000352 Strings support a large number of methods for
Georg Brandl116aa622007-08-15 14:28:22 +0000353 basic transformations and searching.
354
355 :ref:`string-formatting`
Benjamin Petersone6f00632008-05-26 01:03:56 +0000356 Information about string formatting with :meth:`str.format` is described
357 here.
358
359 :ref:`old-string-formatting`
360 The old formatting operations invoked when strings and Unicode strings are
361 the left operand of the ``%`` operator are described in more detail here.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364.. _tut-lists:
365
366Lists
367-----
368
369Python knows a number of *compound* data types, used to group together other
370values. The most versatile is the *list*, which can be written as a list of
Ezio Melotti86aecc32013-05-20 08:12:32 +0300371comma-separated values (items) between square brackets. Lists might contain
372items of different types, but usually the items all have the same type. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Larry Hastings3732ed22014-03-15 21:13:56 -0700374 >>> squares = [1, 4, 9, 16, 25]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300375 >>> squares
Larry Hastings3732ed22014-03-15 21:13:56 -0700376 [1, 4, 9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Ezio Melotti86aecc32013-05-20 08:12:32 +0300378Like strings (and all other built-in :term:`sequence` type), lists can be
379indexed and sliced::
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Ezio Melotti86aecc32013-05-20 08:12:32 +0300381 >>> squares[0] # indexing returns the item
382 1
383 >>> squares[-1]
384 25
385 >>> squares[-3:] # slicing returns a new list
386 [9, 16, 25]
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Benjamin Peterson886af962010-03-21 23:13:07 +0000388All slice operations return a new list containing the requested elements. This
Ezio Melotti86aecc32013-05-20 08:12:32 +0300389means that the following slice returns a new (shallow) copy of the list::
Benjamin Peterson886af962010-03-21 23:13:07 +0000390
Ezio Melotti86aecc32013-05-20 08:12:32 +0300391 >>> squares[:]
Larry Hastings3732ed22014-03-15 21:13:56 -0700392 [1, 4, 9, 16, 25]
Benjamin Peterson886af962010-03-21 23:13:07 +0000393
Ezio Melotti86aecc32013-05-20 08:12:32 +0300394Lists also supports operations like concatenation::
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Ezio Melotti86aecc32013-05-20 08:12:32 +0300396 >>> squares + [36, 49, 64, 81, 100]
Larry Hastings3732ed22014-03-15 21:13:56 -0700397 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300398
399Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
400type, i.e. it is possible to change their content::
401
402 >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
403 >>> 4 ** 3 # the cube of 4 is 64, not 65!
404 64
405 >>> cubes[3] = 64 # replace the wrong value
406 >>> cubes
407 [1, 8, 27, 64, 125]
408
409You can also add new items at the end of the list, by using
410the :meth:`~list.append` *method* (we will see more about methods later)::
411
412 >>> cubes.append(216) # add the cube of 6
413 >>> cubes.append(7 ** 3) # and the cube of 7
414 >>> cubes
415 [1, 8, 27, 64, 125, 216, 343]
Georg Brandl116aa622007-08-15 14:28:22 +0000416
417Assignment to slices is also possible, and this can even change the size of the
418list or clear it entirely::
419
Ezio Melotti86aecc32013-05-20 08:12:32 +0300420 >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
421 >>> letters
422 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
423 >>> # replace some values
424 >>> letters[2:5] = ['C', 'D', 'E']
425 >>> letters
426 ['a', 'b', 'C', 'D', 'E', 'f', 'g']
427 >>> # now remove them
428 >>> letters[2:5] = []
429 >>> letters
430 ['a', 'b', 'f', 'g']
431 >>> # clear the list by replacing all the elements with an empty list
432 >>> letters[:] = []
433 >>> letters
Georg Brandl116aa622007-08-15 14:28:22 +0000434 []
435
436The built-in function :func:`len` also applies to lists::
437
Ezio Melotti86aecc32013-05-20 08:12:32 +0300438 >>> letters = ['a', 'b', 'c', 'd']
439 >>> len(letters)
Guido van Rossum58da9312007-11-10 23:39:45 +0000440 4
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442It is possible to nest lists (create lists containing other lists), for
443example::
444
Ezio Melotti86aecc32013-05-20 08:12:32 +0300445 >>> a = ['a', 'b', 'c']
446 >>> n = [1, 2, 3]
447 >>> x = [a, n]
448 >>> x
449 [['a', 'b', 'c'], [1, 2, 3]]
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300450 >>> x[0]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300451 ['a', 'b', 'c']
Serhiy Storchakafef952a2013-05-28 12:49:34 +0300452 >>> x[0][1]
Ezio Melotti86aecc32013-05-20 08:12:32 +0300453 'b'
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455.. _tut-firststeps:
456
457First Steps Towards Programming
458===============================
459
460Of course, we can use Python for more complicated tasks than adding two and two
461together. For instance, we can write an initial sub-sequence of the *Fibonacci*
462series as follows::
463
464 >>> # Fibonacci series:
465 ... # the sum of two elements defines the next
466 ... a, b = 0, 1
467 >>> while b < 10:
Georg Brandl22ec03c2008-01-07 17:32:13 +0000468 ... print(b)
469 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000470 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000471 1
472 1
473 2
474 3
475 5
476 8
477
478This example introduces several new features.
479
480* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
481 simultaneously get the new values 0 and 1. On the last line this is used again,
482 demonstrating that the expressions on the right-hand side are all evaluated
483 first before any of the assignments take place. The right-hand side expressions
484 are evaluated from the left to the right.
485
486* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
487 remains true. In Python, like in C, any non-zero integer value is true; zero is
488 false. The condition may also be a string or list value, in fact any sequence;
489 anything with a non-zero length is true, empty sequences are false. The test
490 used in the example is a simple comparison. The standard comparison operators
491 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
492 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
493 and ``!=`` (not equal to).
494
495* The *body* of the loop is *indented*: indentation is Python's way of grouping
Georg Brandl1532c8f2011-12-25 19:03:07 +0100496 statements. At the interactive prompt, you have to type a tab or space(s) for
497 each indented line. In practice you will prepare more complicated input
498 for Python with a text editor; all decent text editors have an auto-indent
499 facility. When a compound statement is entered interactively, it must be
500 followed by a blank line to indicate completion (since the parser cannot
501 guess when you have typed the last line). Note that each line within a basic
502 block must be indented by the same amount.
Georg Brandl116aa622007-08-15 14:28:22 +0000503
Benjamin Peterson07819002013-01-20 10:05:13 -0500504* The :func:`print` function writes the value of the argument(s) it is given.
505 It differs from just writing the expression you want to write (as we did
506 earlier in the calculator examples) in the way it handles multiple arguments,
507 floating point quantities, and strings. Strings are printed without quotes,
508 and a space is inserted between items, so you can format things nicely, like
509 this::
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 >>> i = 256*256
Guido van Rossum0616b792007-08-31 03:25:11 +0000512 >>> print('The value of i is', i)
Georg Brandl116aa622007-08-15 14:28:22 +0000513 The value of i is 65536
514
Benjamin Peterson648fa192013-01-20 10:09:44 -0500515 The keyword argument *end* can be used to avoid the newline after the output,
516 or end the output with a different string::
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518 >>> a, b = 0, 1
519 >>> while b < 1000:
Terry Reedy02a807e2010-11-12 04:22:22 +0000520 ... print(b, end=',')
Georg Brandl116aa622007-08-15 14:28:22 +0000521 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000522 ...
Terry Reedy02a807e2010-11-12 04:22:22 +0000523 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Ezio Melotti86aecc32013-05-20 08:12:32 +0300524
525
526.. rubric:: Footnotes
527
528.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
529 interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this
530 and get ``9``, you can use ``(-3)**2``.
531
532.. [#] Unlike other languages, special characters such as ``\n`` have the
533 same meaning with both single (``'...'``) and double (``"..."``) quotes.
534 The only difference between the two is that within single quotes you don't
535 need to escape ``"`` (but you have to escape ``\'``) and vice versa.