blob: c07a668ccb9dedb7456135d5dabaef15029a6b52 [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
8absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
9everything 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
25 SPAM = 1 # and this is the second comment
26 # ... and now a third!
27 STRING = "# This is not a comment."
28
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
47(for example, Pascal or C); parentheses can be used for grouping. For example::
48
49 >>> 2+2
50 4
51 >>> # This is a comment
52 ... 2+2
53 4
54 >>> 2+2 # and a comment on the same line as code
55 4
56 >>> (50-5*6)/4
Guido van Rossum0616b792007-08-31 03:25:11 +000057 5.0
58 >>> 8/5 # Fractions aren't lost when dividing integers
Mark Dickinson5a55b612009-06-28 20:59:42 +000059 1.6
Guido van Rossum0616b792007-08-31 03:25:11 +000060
Georg Brandl48310cd2009-01-03 21:18:54 +000061Note: You might not see exactly the same result; floating point results can
Guido van Rossum0616b792007-08-31 03:25:11 +000062differ from one machine to another. We will say more later about controlling
Mark Dickinsonaf15f3c2009-06-28 21:19:18 +000063the appearance of floating point output. See also :ref:`tut-fp-issues` for a
64full discussion of some of the subtleties of floating point numbers and their
65representations.
Guido van Rossum0616b792007-08-31 03:25:11 +000066
Georg Brandl48310cd2009-01-03 21:18:54 +000067To do integer division and get an integer result,
Guido van Rossum0616b792007-08-31 03:25:11 +000068discarding any fractional result, there is another operator, ``//``::
Georg Brandl48310cd2009-01-03 21:18:54 +000069
Georg Brandl116aa622007-08-15 14:28:22 +000070 >>> # Integer division returns the floor:
Guido van Rossum0616b792007-08-31 03:25:11 +000071 ... 7//3
Georg Brandl116aa622007-08-15 14:28:22 +000072 2
Guido van Rossum0616b792007-08-31 03:25:11 +000073 >>> 7//-3
Georg Brandl116aa622007-08-15 14:28:22 +000074 -3
75
76The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
77result is displayed before the next interactive prompt::
78
79 >>> width = 20
80 >>> height = 5*9
81 >>> width * height
82 900
83
84A value can be assigned to several variables simultaneously::
85
86 >>> x = y = z = 0 # Zero x, y and z
87 >>> x
88 0
89 >>> y
90 0
91 >>> z
92 0
93
Georg Brandl5d955ed2008-09-13 17:18:21 +000094Variables must be "defined" (assigned a value) before they can be used, or an
95error will occur::
96
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
105 >>> 3 * 3.75 / 1.5
106 7.5
107 >>> 7.0 / 2
108 3.5
109
110Complex numbers are also supported; imaginary numbers are written with a suffix
111of ``j`` or ``J``. Complex numbers with a nonzero real component are written as
112``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
113::
114
115 >>> 1j * 1J
116 (-1+0j)
Georg Brandle4ac7502007-09-03 07:10:24 +0000117 >>> 1j * complex(0, 1)
Georg Brandl116aa622007-08-15 14:28:22 +0000118 (-1+0j)
119 >>> 3+1j*3
120 (3+3j)
121 >>> (3+1j)*3
122 (9+3j)
123 >>> (1+2j)/(1+1j)
124 (1.5+0.5j)
125
126Complex numbers are always represented as two floating point numbers, the real
127and imaginary part. To extract these parts from a complex number *z*, use
128``z.real`` and ``z.imag``. ::
129
130 >>> a=1.5+0.5j
131 >>> a.real
132 1.5
133 >>> a.imag
134 0.5
135
136The conversion functions to floating point and integer (:func:`float`,
Georg Brandl2d2590d2007-09-28 13:13:35 +0000137:func:`int`) don't work for complex numbers --- there is not one correct way to
138convert a complex number to a real number. Use ``abs(z)`` to get its magnitude
139(as a float) or ``z.real`` to get its real part::
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 >>> a=3.0+4.0j
142 >>> float(a)
143 Traceback (most recent call last):
144 File "<stdin>", line 1, in ?
145 TypeError: can't convert complex to float; use abs(z)
146 >>> a.real
147 3.0
148 >>> a.imag
149 4.0
150 >>> abs(a) # sqrt(a.real**2 + a.imag**2)
151 5.0
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153In interactive mode, the last printed expression is assigned to the variable
154``_``. This means that when you are using Python as a desk calculator, it is
155somewhat easier to continue calculations, for example::
156
157 >>> tax = 12.5 / 100
158 >>> price = 100.50
159 >>> price * tax
160 12.5625
161 >>> price + _
162 113.0625
163 >>> round(_, 2)
164 113.06
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166This variable should be treated as read-only by the user. Don't explicitly
167assign a value to it --- you would create an independent local variable with the
168same name masking the built-in variable with its magic behavior.
169
170
171.. _tut-strings:
172
173Strings
174-------
175
176Besides numbers, Python can also manipulate strings, which can be expressed in
177several ways. They can be enclosed in single quotes or double quotes::
178
179 >>> 'spam eggs'
180 'spam eggs'
181 >>> 'doesn\'t'
182 "doesn't"
183 >>> "doesn't"
184 "doesn't"
185 >>> '"Yes," he said.'
186 '"Yes," he said.'
187 >>> "\"Yes,\" he said."
188 '"Yes," he said.'
189 >>> '"Isn\'t," she said.'
190 '"Isn\'t," she said.'
191
Guido van Rossum0616b792007-08-31 03:25:11 +0000192The interpreter prints the result of string operations in the same way as they
193are typed for input: inside quotes, and with quotes and other funny characters
194escaped by backslashes, to show the precise value. The string is enclosed in
195double quotes if the string contains a single quote and no double quotes, else
Senthil Kumaranc64cb6f2010-11-08 02:04:05 +0000196it's enclosed in single quotes. The :func:`print` function produces a more
Senthil Kumarana0fa1ce2010-11-08 01:53:13 +0000197readable output for such input strings.
Guido van Rossum0616b792007-08-31 03:25:11 +0000198
Georg Brandl116aa622007-08-15 14:28:22 +0000199String literals can span multiple lines in several ways. Continuation lines can
200be used, with a backslash as the last character on the line indicating that the
201next line is a logical continuation of the line::
202
203 hello = "This is a rather long string containing\n\
204 several lines of text just as you would do in C.\n\
205 Note that whitespace at the beginning of the line is\
206 significant."
207
Guido van Rossum0616b792007-08-31 03:25:11 +0000208 print(hello)
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000210Note that newlines still need to be embedded in the string using ``\n`` -- the
Georg Brandl116aa622007-08-15 14:28:22 +0000211newline following the trailing backslash is discarded. This example would print
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000212the following:
213
214.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216 This is a rather long string containing
217 several lines of text just as you would do in C.
218 Note that whitespace at the beginning of the line is significant.
219
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000220Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
221``'''``. End of lines do not need to be escaped when using triple-quotes, but
Terry Reedy02a807e2010-11-12 04:22:22 +0000222they will be included in the string. So the following uses one escape to
223avoid an unwanted initial blank line. ::
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000224
Terry Reedy02a807e2010-11-12 04:22:22 +0000225 print("""\
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000226 Usage: thingy [OPTIONS]
227 -h Display this usage message
228 -H hostname Hostname to connect to
Ezio Melottib297e712009-09-25 20:14:02 +0000229 """)
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000230
231produces the following output:
232
233.. code-block:: text
234
235 Usage: thingy [OPTIONS]
236 -h Display this usage message
237 -H hostname Hostname to connect to
238
Benjamin Petersond23f8222009-04-05 19:13:16 +0000239If we make the string literal a "raw" string, ``\n`` sequences are not converted
240to newlines, but the backslash at the end of the line, and the newline character
241in the source, are both included in the string as data. Thus, the example::
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243 hello = r"This is a rather long string containing\n\
244 several lines of text much as you would do in C."
245
Guido van Rossum0616b792007-08-31 03:25:11 +0000246 print(hello)
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000248would print:
249
250.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252 This is a rather long string containing\n\
253 several lines of text much as you would do in C.
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255Strings can be concatenated (glued together) with the ``+`` operator, and
256repeated with ``*``::
257
258 >>> word = 'Help' + 'A'
259 >>> word
260 'HelpA'
261 >>> '<' + word*5 + '>'
262 '<HelpAHelpAHelpAHelpAHelpA>'
263
264Two string literals next to each other are automatically concatenated; the first
265line above could also have been written ``word = 'Help' 'A'``; this only works
266with two literals, not with arbitrary string expressions::
267
268 >>> 'str' 'ing' # <- This is ok
269 'string'
270 >>> 'str'.strip() + 'ing' # <- This is ok
271 'string'
272 >>> 'str'.strip() 'ing' # <- This is invalid
273 File "<stdin>", line 1, in ?
274 'str'.strip() 'ing'
275 ^
276 SyntaxError: invalid syntax
277
278Strings can be subscripted (indexed); like in C, the first character of a string
279has subscript (index) 0. There is no separate character type; a character is
Georg Brandle4ac7502007-09-03 07:10:24 +0000280simply a string of size one. As in the Icon programming language, substrings
281can be specified with the *slice notation*: two indices separated by a colon.
282::
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284 >>> word[4]
285 'A'
286 >>> word[0:2]
287 'He'
288 >>> word[2:4]
289 'lp'
290
291Slice indices have useful defaults; an omitted first index defaults to zero, an
292omitted second index defaults to the size of the string being sliced. ::
293
294 >>> word[:2] # The first two characters
295 'He'
296 >>> word[2:] # Everything except the first two characters
297 'lpA'
298
Georg Brandl5d955ed2008-09-13 17:18:21 +0000299Unlike a C string, Python strings cannot be changed. Assigning to an indexed
Georg Brandl116aa622007-08-15 14:28:22 +0000300position in the string results in an error::
301
302 >>> word[0] = 'x'
303 Traceback (most recent call last):
304 File "<stdin>", line 1, in ?
Georg Brandl7fcb3bf2009-05-17 08:18:02 +0000305 TypeError: 'str' object does not support item assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000306 >>> word[:1] = 'Splat'
307 Traceback (most recent call last):
308 File "<stdin>", line 1, in ?
Georg Brandl7fcb3bf2009-05-17 08:18:02 +0000309 TypeError: 'str' object does not support slice assignment
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311However, creating a new string with the combined content is easy and efficient::
312
313 >>> 'x' + word[1:]
314 'xelpA'
315 >>> 'Splat' + word[4]
316 'SplatA'
317
318Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
319::
320
321 >>> word[:2] + word[2:]
322 'HelpA'
323 >>> word[:3] + word[3:]
324 'HelpA'
325
326Degenerate slice indices are handled gracefully: an index that is too large is
327replaced by the string size, an upper bound smaller than the lower bound returns
328an empty string. ::
329
330 >>> word[1:100]
331 'elpA'
332 >>> word[10:]
333 ''
334 >>> word[2:1]
335 ''
336
337Indices may be negative numbers, to start counting from the right. For example::
338
339 >>> word[-1] # The last character
340 'A'
341 >>> word[-2] # The last-but-one character
342 'p'
343 >>> word[-2:] # The last two characters
344 'pA'
345 >>> word[:-2] # Everything except the last two characters
346 'Hel'
347
348But note that -0 is really the same as 0, so it does not count from the right!
349::
350
351 >>> word[-0] # (since -0 equals 0)
352 'H'
353
354Out-of-range negative slice indices are truncated, but don't try this for
355single-element (non-slice) indices::
356
357 >>> word[-100:]
358 'HelpA'
359 >>> word[-10] # error
360 Traceback (most recent call last):
361 File "<stdin>", line 1, in ?
362 IndexError: string index out of range
363
364One way to remember how slices work is to think of the indices as pointing
365*between* characters, with the left edge of the first character numbered 0.
366Then the right edge of the last character of a string of *n* characters has
367index *n*, for example::
368
Georg Brandl48310cd2009-01-03 21:18:54 +0000369 +---+---+---+---+---+
Georg Brandl116aa622007-08-15 14:28:22 +0000370 | H | e | l | p | A |
Georg Brandl48310cd2009-01-03 21:18:54 +0000371 +---+---+---+---+---+
372 0 1 2 3 4 5
Georg Brandl116aa622007-08-15 14:28:22 +0000373 -5 -4 -3 -2 -1
374
375The first row of numbers gives the position of the indices 0...5 in the string;
376the second row gives the corresponding negative indices. The slice from *i* to
377*j* consists of all characters between the edges labeled *i* and *j*,
378respectively.
379
380For non-negative indices, the length of a slice is the difference of the
381indices, if both are within bounds. For example, the length of ``word[1:3]`` is
3822.
383
384The built-in function :func:`len` returns the length of a string::
385
386 >>> s = 'supercalifragilisticexpialidocious'
387 >>> len(s)
388 34
389
390
391.. seealso::
392
Ezio Melottia6229e62012-10-12 10:59:14 +0300393 :ref:`textseq`
Georg Brandl48310cd2009-01-03 21:18:54 +0000394 Strings are examples of *sequence types*, and support the common
Guido van Rossum0616b792007-08-31 03:25:11 +0000395 operations supported by such types.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397 :ref:`string-methods`
Guido van Rossum0616b792007-08-31 03:25:11 +0000398 Strings support a large number of methods for
Georg Brandl116aa622007-08-15 14:28:22 +0000399 basic transformations and searching.
400
401 :ref:`string-formatting`
Benjamin Petersone6f00632008-05-26 01:03:56 +0000402 Information about string formatting with :meth:`str.format` is described
403 here.
404
405 :ref:`old-string-formatting`
406 The old formatting operations invoked when strings and Unicode strings are
407 the left operand of the ``%`` operator are described in more detail here.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409
410.. _tut-unicodestrings:
411
Guido van Rossum0616b792007-08-31 03:25:11 +0000412About Unicode
413-------------
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Antoine Pitroufbd4f802012-08-11 16:51:50 +0200415.. sectionauthor:: Marc-André Lemburg <mal@lemburg.com>
Georg Brandl116aa622007-08-15 14:28:22 +0000416
417
Georg Brandl5d955ed2008-09-13 17:18:21 +0000418Starting with Python 3.0 all strings support Unicode (see
419http://www.unicode.org/).
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421Unicode has the advantage of providing one ordinal for every character in every
422script used in modern and ancient texts. Previously, there were only 256
423possible ordinals for script characters. Texts were typically bound to a code
424page which mapped the ordinals to script characters. This lead to very much
425confusion especially with respect to internationalization (usually written as
426``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
427these problems by defining one code page for all scripts.
428
Guido van Rossum0616b792007-08-31 03:25:11 +0000429If you want to include special characters in a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000430you can do so by using the Python *Unicode-Escape* encoding. The following
431example shows how::
432
Guido van Rossum0616b792007-08-31 03:25:11 +0000433 >>> 'Hello\u0020World !'
434 'Hello World !'
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436The escape sequence ``\u0020`` indicates to insert the Unicode character with
437the ordinal value 0x0020 (the space character) at the given position.
438
439Other characters are interpreted by using their respective ordinal values
440directly as Unicode ordinals. If you have literal strings in the standard
441Latin-1 encoding that is used in many Western countries, you will find it
442convenient that the lower 256 characters of Unicode are the same as the 256
443characters of Latin-1.
444
Georg Brandl116aa622007-08-15 14:28:22 +0000445Apart from these standard encodings, Python provides a whole set of other ways
446of creating Unicode strings on the basis of a known encoding.
447
Guido van Rossum0616b792007-08-31 03:25:11 +0000448To convert a string into a sequence of bytes using a specific encoding,
449string objects provide an :func:`encode` method that takes one argument, the
Georg Brandl116aa622007-08-15 14:28:22 +0000450name of the encoding. Lowercase names for encodings are preferred. ::
451
Georg Brandlc3f5bad2007-08-31 06:46:05 +0000452 >>> "Äpfel".encode('utf-8')
453 b'\xc3\x84pfel'
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455.. _tut-lists:
456
457Lists
458-----
459
460Python knows a number of *compound* data types, used to group together other
461values. The most versatile is the *list*, which can be written as a list of
462comma-separated values (items) between square brackets. List items need not all
463have the same type. ::
464
465 >>> a = ['spam', 'eggs', 100, 1234]
466 >>> a
467 ['spam', 'eggs', 100, 1234]
468
469Like string indices, list indices start at 0, and lists can be sliced,
470concatenated and so on::
471
472 >>> a[0]
473 'spam'
474 >>> a[3]
475 1234
476 >>> a[-2]
477 100
478 >>> a[1:-1]
479 ['eggs', 100]
480 >>> a[:2] + ['bacon', 2*2]
481 ['spam', 'eggs', 'bacon', 4]
482 >>> 3*a[:3] + ['Boo!']
483 ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
484
Benjamin Peterson886af962010-03-21 23:13:07 +0000485All slice operations return a new list containing the requested elements. This
486means that the following slice returns a shallow copy of the list *a*::
487
488 >>> a[:]
489 ['spam', 'eggs', 100, 1234]
490
Georg Brandl116aa622007-08-15 14:28:22 +0000491Unlike strings, which are *immutable*, it is possible to change individual
492elements of a list::
493
494 >>> a
495 ['spam', 'eggs', 100, 1234]
496 >>> a[2] = a[2] + 23
497 >>> a
498 ['spam', 'eggs', 123, 1234]
499
500Assignment to slices is also possible, and this can even change the size of the
501list or clear it entirely::
502
503 >>> # Replace some items:
504 ... a[0:2] = [1, 12]
505 >>> a
506 [1, 12, 123, 1234]
507 >>> # Remove some:
508 ... a[0:2] = []
509 >>> a
510 [123, 1234]
511 >>> # Insert some:
512 ... a[1:1] = ['bletch', 'xyzzy']
513 >>> a
514 [123, 'bletch', 'xyzzy', 1234]
515 >>> # Insert (a copy of) itself at the beginning
516 >>> a[:0] = a
517 >>> a
518 [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
519 >>> # Clear the list: replace all items with an empty list
520 >>> a[:] = []
521 >>> a
522 []
523
524The built-in function :func:`len` also applies to lists::
525
Guido van Rossum58da9312007-11-10 23:39:45 +0000526 >>> a = ['a', 'b', 'c', 'd']
Georg Brandl116aa622007-08-15 14:28:22 +0000527 >>> len(a)
Guido van Rossum58da9312007-11-10 23:39:45 +0000528 4
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530It is possible to nest lists (create lists containing other lists), for
531example::
532
533 >>> q = [2, 3]
534 >>> p = [1, q, 4]
535 >>> len(p)
536 3
537 >>> p[1]
538 [2, 3]
539 >>> p[1][0]
540 2
Guido van Rossum0616b792007-08-31 03:25:11 +0000541
542You can add something to the end of the list::
543
Georg Brandle4ac7502007-09-03 07:10:24 +0000544 >>> p[1].append('xtra')
Georg Brandl116aa622007-08-15 14:28:22 +0000545 >>> p
546 [1, [2, 3, 'xtra'], 4]
547 >>> q
548 [2, 3, 'xtra']
549
550Note that in the last example, ``p[1]`` and ``q`` really refer to the same
551object! We'll come back to *object semantics* later.
552
553
554.. _tut-firststeps:
555
556First Steps Towards Programming
557===============================
558
559Of course, we can use Python for more complicated tasks than adding two and two
560together. For instance, we can write an initial sub-sequence of the *Fibonacci*
561series as follows::
562
563 >>> # Fibonacci series:
564 ... # the sum of two elements defines the next
565 ... a, b = 0, 1
566 >>> while b < 10:
Georg Brandl22ec03c2008-01-07 17:32:13 +0000567 ... print(b)
568 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000569 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000570 1
571 1
572 2
573 3
574 5
575 8
576
577This example introduces several new features.
578
579* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
580 simultaneously get the new values 0 and 1. On the last line this is used again,
581 demonstrating that the expressions on the right-hand side are all evaluated
582 first before any of the assignments take place. The right-hand side expressions
583 are evaluated from the left to the right.
584
585* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
586 remains true. In Python, like in C, any non-zero integer value is true; zero is
587 false. The condition may also be a string or list value, in fact any sequence;
588 anything with a non-zero length is true, empty sequences are false. The test
589 used in the example is a simple comparison. The standard comparison operators
590 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
591 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
592 and ``!=`` (not equal to).
593
594* The *body* of the loop is *indented*: indentation is Python's way of grouping
Georg Brandl1532c8f2011-12-25 19:03:07 +0100595 statements. At the interactive prompt, you have to type a tab or space(s) for
596 each indented line. In practice you will prepare more complicated input
597 for Python with a text editor; all decent text editors have an auto-indent
598 facility. When a compound statement is entered interactively, it must be
599 followed by a blank line to indicate completion (since the parser cannot
600 guess when you have typed the last line). Note that each line within a basic
601 block must be indented by the same amount.
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Guido van Rossum0616b792007-08-31 03:25:11 +0000603* The :func:`print` function writes the value of the expression(s) it is
Georg Brandl116aa622007-08-15 14:28:22 +0000604 given. It differs from just writing the expression you want to write (as we did
Georg Brandl48310cd2009-01-03 21:18:54 +0000605 earlier in the calculator examples) in the way it handles multiple
606 expressions, floating point quantities,
Georg Brandl116aa622007-08-15 14:28:22 +0000607 and strings. Strings are printed without quotes, and a space is inserted
608 between items, so you can format things nicely, like this::
609
610 >>> i = 256*256
Guido van Rossum0616b792007-08-31 03:25:11 +0000611 >>> print('The value of i is', i)
Georg Brandl116aa622007-08-15 14:28:22 +0000612 The value of i is 65536
613
Georg Brandl11e18b02008-08-05 09:04:16 +0000614 The keyword *end* can be used to avoid the newline after the output, or end
615 the output with a different string::
Georg Brandl116aa622007-08-15 14:28:22 +0000616
617 >>> a, b = 0, 1
618 >>> while b < 1000:
Terry Reedy02a807e2010-11-12 04:22:22 +0000619 ... print(b, end=',')
Georg Brandl116aa622007-08-15 14:28:22 +0000620 ... a, b = b, a+b
Georg Brandl48310cd2009-01-03 21:18:54 +0000621 ...
Terry Reedy02a807e2010-11-12 04:22:22 +0000622 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,