/Doc/tutorial/introduction.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 651 lines · 512 code · 139 blank · 0 comment · 0 complexity · 30f5aa970da0aee2332868fcab690810 MD5 · raw file

  1. .. _tut-informal:
  2. **********************************
  3. An Informal Introduction to Python
  4. **********************************
  5. In the following examples, input and output are distinguished by the presence or
  6. absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
  7. everything after the prompt, when the prompt appears; lines that do not begin
  8. with a prompt are output from the interpreter. Note that a secondary prompt on a
  9. line by itself in an example means you must type a blank line; this is used to
  10. end a multi-line command.
  11. Many of the examples in this manual, even those entered at the interactive
  12. prompt, include comments. Comments in Python start with the hash character,
  13. ``#``, and extend to the end of the physical line. A comment may appear at the
  14. start of a line or following whitespace or code, but not within a string
  15. literal. A hash character within a string literal is just a hash character.
  16. Since comments are to clarify code and are not interpreted by Python, they may
  17. be omitted when typing in examples.
  18. Some examples::
  19. # this is the first comment
  20. SPAM = 1 # and this is the second comment
  21. # ... and now a third!
  22. STRING = "# This is not a comment."
  23. .. _tut-calculator:
  24. Using Python as a Calculator
  25. ============================
  26. Let's try some simple Python commands. Start the interpreter and wait for the
  27. primary prompt, ``>>>``. (It shouldn't take long.)
  28. .. _tut-numbers:
  29. Numbers
  30. -------
  31. The interpreter acts as a simple calculator: you can type an expression at it
  32. and it will write the value. Expression syntax is straightforward: the
  33. operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
  34. (for example, Pascal or C); parentheses can be used for grouping. For example::
  35. >>> 2+2
  36. 4
  37. >>> # This is a comment
  38. ... 2+2
  39. 4
  40. >>> 2+2 # and a comment on the same line as code
  41. 4
  42. >>> (50-5*6)/4
  43. 5
  44. >>> # Integer division returns the floor:
  45. ... 7/3
  46. 2
  47. >>> 7/-3
  48. -3
  49. The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
  50. result is displayed before the next interactive prompt::
  51. >>> width = 20
  52. >>> height = 5*9
  53. >>> width * height
  54. 900
  55. A value can be assigned to several variables simultaneously::
  56. >>> x = y = z = 0 # Zero x, y and z
  57. >>> x
  58. 0
  59. >>> y
  60. 0
  61. >>> z
  62. 0
  63. Variables must be "defined" (assigned a value) before they can be used, or an
  64. error will occur::
  65. >>> # try to access an undefined variable
  66. ... n
  67. Traceback (most recent call last):
  68. File "<stdin>", line 1, in <module>
  69. NameError: name 'n' is not defined
  70. There is full support for floating point; operators with mixed type operands
  71. convert the integer operand to floating point::
  72. >>> 3 * 3.75 / 1.5
  73. 7.5
  74. >>> 7.0 / 2
  75. 3.5
  76. Complex numbers are also supported; imaginary numbers are written with a suffix
  77. of ``j`` or ``J``. Complex numbers with a nonzero real component are written as
  78. ``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
  79. ::
  80. >>> 1j * 1J
  81. (-1+0j)
  82. >>> 1j * complex(0,1)
  83. (-1+0j)
  84. >>> 3+1j*3
  85. (3+3j)
  86. >>> (3+1j)*3
  87. (9+3j)
  88. >>> (1+2j)/(1+1j)
  89. (1.5+0.5j)
  90. Complex numbers are always represented as two floating point numbers, the real
  91. and imaginary part. To extract these parts from a complex number *z*, use
  92. ``z.real`` and ``z.imag``. ::
  93. >>> a=1.5+0.5j
  94. >>> a.real
  95. 1.5
  96. >>> a.imag
  97. 0.5
  98. The conversion functions to floating point and integer (:func:`float`,
  99. :func:`int` and :func:`long`) don't work for complex numbers --- there is no one
  100. correct way to convert a complex number to a real number. Use ``abs(z)`` to get
  101. its magnitude (as a float) or ``z.real`` to get its real part. ::
  102. >>> a=3.0+4.0j
  103. >>> float(a)
  104. Traceback (most recent call last):
  105. File "<stdin>", line 1, in ?
  106. TypeError: can't convert complex to float; use abs(z)
  107. >>> a.real
  108. 3.0
  109. >>> a.imag
  110. 4.0
  111. >>> abs(a) # sqrt(a.real**2 + a.imag**2)
  112. 5.0
  113. >>>
  114. In interactive mode, the last printed expression is assigned to the variable
  115. ``_``. This means that when you are using Python as a desk calculator, it is
  116. somewhat easier to continue calculations, for example::
  117. >>> tax = 12.5 / 100
  118. >>> price = 100.50
  119. >>> price * tax
  120. 12.5625
  121. >>> price + _
  122. 113.0625
  123. >>> round(_, 2)
  124. 113.06
  125. >>>
  126. This variable should be treated as read-only by the user. Don't explicitly
  127. assign a value to it --- you would create an independent local variable with the
  128. same name masking the built-in variable with its magic behavior.
  129. .. _tut-strings:
  130. Strings
  131. -------
  132. Besides numbers, Python can also manipulate strings, which can be expressed in
  133. several ways. They can be enclosed in single quotes or double quotes::
  134. >>> 'spam eggs'
  135. 'spam eggs'
  136. >>> 'doesn\'t'
  137. "doesn't"
  138. >>> "doesn't"
  139. "doesn't"
  140. >>> '"Yes," he said.'
  141. '"Yes," he said.'
  142. >>> "\"Yes,\" he said."
  143. '"Yes," he said.'
  144. >>> '"Isn\'t," she said.'
  145. '"Isn\'t," she said.'
  146. String literals can span multiple lines in several ways. Continuation lines can
  147. be used, with a backslash as the last character on the line indicating that the
  148. next line is a logical continuation of the line::
  149. hello = "This is a rather long string containing\n\
  150. several lines of text just as you would do in C.\n\
  151. Note that whitespace at the beginning of the line is\
  152. significant."
  153. print hello
  154. Note that newlines still need to be embedded in the string using ``\n``; the
  155. newline following the trailing backslash is discarded. This example would print
  156. the following::
  157. This is a rather long string containing
  158. several lines of text just as you would do in C.
  159. Note that whitespace at the beginning of the line is significant.
  160. Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
  161. ``'''``. End of lines do not need to be escaped when using triple-quotes, but
  162. they will be included in the string. ::
  163. print """
  164. Usage: thingy [OPTIONS]
  165. -h Display this usage message
  166. -H hostname Hostname to connect to
  167. """
  168. produces the following output::
  169. Usage: thingy [OPTIONS]
  170. -h Display this usage message
  171. -H hostname Hostname to connect to
  172. If we make the string literal a "raw" string, ``\n`` sequences are not converted
  173. to newlines, but the backslash at the end of the line, and the newline character
  174. in the source, are both included in the string as data. Thus, the example::
  175. hello = r"This is a rather long string containing\n\
  176. several lines of text much as you would do in C."
  177. print hello
  178. would print::
  179. This is a rather long string containing\n\
  180. several lines of text much as you would do in C.
  181. The interpreter prints the result of string operations in the same way as they
  182. are typed for input: inside quotes, and with quotes and other funny characters
  183. escaped by backslashes, to show the precise value. The string is enclosed in
  184. double quotes if the string contains a single quote and no double quotes, else
  185. it's enclosed in single quotes. (The :keyword:`print` statement, described
  186. later, can be used to write strings without quotes or escapes.)
  187. Strings can be concatenated (glued together) with the ``+`` operator, and
  188. repeated with ``*``::
  189. >>> word = 'Help' + 'A'
  190. >>> word
  191. 'HelpA'
  192. >>> '<' + word*5 + '>'
  193. '<HelpAHelpAHelpAHelpAHelpA>'
  194. Two string literals next to each other are automatically concatenated; the first
  195. line above could also have been written ``word = 'Help' 'A'``; this only works
  196. with two literals, not with arbitrary string expressions::
  197. >>> 'str' 'ing' # <- This is ok
  198. 'string'
  199. >>> 'str'.strip() + 'ing' # <- This is ok
  200. 'string'
  201. >>> 'str'.strip() 'ing' # <- This is invalid
  202. File "<stdin>", line 1, in ?
  203. 'str'.strip() 'ing'
  204. ^
  205. SyntaxError: invalid syntax
  206. Strings can be subscripted (indexed); like in C, the first character of a string
  207. has subscript (index) 0. There is no separate character type; a character is
  208. simply a string of size one. Like in Icon, substrings can be specified with the
  209. *slice notation*: two indices separated by a colon. ::
  210. >>> word[4]
  211. 'A'
  212. >>> word[0:2]
  213. 'He'
  214. >>> word[2:4]
  215. 'lp'
  216. Slice indices have useful defaults; an omitted first index defaults to zero, an
  217. omitted second index defaults to the size of the string being sliced. ::
  218. >>> word[:2] # The first two characters
  219. 'He'
  220. >>> word[2:] # Everything except the first two characters
  221. 'lpA'
  222. Unlike a C string, Python strings cannot be changed. Assigning to an indexed
  223. position in the string results in an error::
  224. >>> word[0] = 'x'
  225. Traceback (most recent call last):
  226. File "<stdin>", line 1, in ?
  227. TypeError: object does not support item assignment
  228. >>> word[:1] = 'Splat'
  229. Traceback (most recent call last):
  230. File "<stdin>", line 1, in ?
  231. TypeError: object does not support slice assignment
  232. However, creating a new string with the combined content is easy and efficient::
  233. >>> 'x' + word[1:]
  234. 'xelpA'
  235. >>> 'Splat' + word[4]
  236. 'SplatA'
  237. Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
  238. ::
  239. >>> word[:2] + word[2:]
  240. 'HelpA'
  241. >>> word[:3] + word[3:]
  242. 'HelpA'
  243. Degenerate slice indices are handled gracefully: an index that is too large is
  244. replaced by the string size, an upper bound smaller than the lower bound returns
  245. an empty string. ::
  246. >>> word[1:100]
  247. 'elpA'
  248. >>> word[10:]
  249. ''
  250. >>> word[2:1]
  251. ''
  252. Indices may be negative numbers, to start counting from the right. For example::
  253. >>> word[-1] # The last character
  254. 'A'
  255. >>> word[-2] # The last-but-one character
  256. 'p'
  257. >>> word[-2:] # The last two characters
  258. 'pA'
  259. >>> word[:-2] # Everything except the last two characters
  260. 'Hel'
  261. But note that -0 is really the same as 0, so it does not count from the right!
  262. ::
  263. >>> word[-0] # (since -0 equals 0)
  264. 'H'
  265. Out-of-range negative slice indices are truncated, but don't try this for
  266. single-element (non-slice) indices::
  267. >>> word[-100:]
  268. 'HelpA'
  269. >>> word[-10] # error
  270. Traceback (most recent call last):
  271. File "<stdin>", line 1, in ?
  272. IndexError: string index out of range
  273. One way to remember how slices work is to think of the indices as pointing
  274. *between* characters, with the left edge of the first character numbered 0.
  275. Then the right edge of the last character of a string of *n* characters has
  276. index *n*, for example::
  277. +---+---+---+---+---+
  278. | H | e | l | p | A |
  279. +---+---+---+---+---+
  280. 0 1 2 3 4 5
  281. -5 -4 -3 -2 -1
  282. The first row of numbers gives the position of the indices 0...5 in the string;
  283. the second row gives the corresponding negative indices. The slice from *i* to
  284. *j* consists of all characters between the edges labeled *i* and *j*,
  285. respectively.
  286. For non-negative indices, the length of a slice is the difference of the
  287. indices, if both are within bounds. For example, the length of ``word[1:3]`` is
  288. 2.
  289. The built-in function :func:`len` returns the length of a string::
  290. >>> s = 'supercalifragilisticexpialidocious'
  291. >>> len(s)
  292. 34
  293. .. seealso::
  294. :ref:`typesseq`
  295. Strings, and the Unicode strings described in the next section, are
  296. examples of *sequence types*, and support the common operations supported
  297. by such types.
  298. :ref:`string-methods`
  299. Both strings and Unicode strings support a large number of methods for
  300. basic transformations and searching.
  301. :ref:`new-string-formatting`
  302. Information about string formatting with :meth:`str.format` is described
  303. here.
  304. :ref:`string-formatting`
  305. The old formatting operations invoked when strings and Unicode strings are
  306. the left operand of the ``%`` operator are described in more detail here.
  307. .. _tut-unicodestrings:
  308. Unicode Strings
  309. ---------------
  310. .. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
  311. Starting with Python 2.0 a new data type for storing text data is available to
  312. the programmer: the Unicode object. It can be used to store and manipulate
  313. Unicode data (see http://www.unicode.org/) and integrates well with the existing
  314. string objects, providing auto-conversions where necessary.
  315. Unicode has the advantage of providing one ordinal for every character in every
  316. script used in modern and ancient texts. Previously, there were only 256
  317. possible ordinals for script characters. Texts were typically bound to a code
  318. page which mapped the ordinals to script characters. This lead to very much
  319. confusion especially with respect to internationalization (usually written as
  320. ``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
  321. these problems by defining one code page for all scripts.
  322. Creating Unicode strings in Python is just as simple as creating normal
  323. strings::
  324. >>> u'Hello World !'
  325. u'Hello World !'
  326. The small ``'u'`` in front of the quote indicates that a Unicode string is
  327. supposed to be created. If you want to include special characters in the string,
  328. you can do so by using the Python *Unicode-Escape* encoding. The following
  329. example shows how::
  330. >>> u'Hello\u0020World !'
  331. u'Hello World !'
  332. The escape sequence ``\u0020`` indicates to insert the Unicode character with
  333. the ordinal value 0x0020 (the space character) at the given position.
  334. Other characters are interpreted by using their respective ordinal values
  335. directly as Unicode ordinals. If you have literal strings in the standard
  336. Latin-1 encoding that is used in many Western countries, you will find it
  337. convenient that the lower 256 characters of Unicode are the same as the 256
  338. characters of Latin-1.
  339. For experts, there is also a raw mode just like the one for normal strings. You
  340. have to prefix the opening quote with 'ur' to have Python use the
  341. *Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
  342. conversion if there is an uneven number of backslashes in front of the small
  343. 'u'. ::
  344. >>> ur'Hello\u0020World !'
  345. u'Hello World !'
  346. >>> ur'Hello\\u0020World !'
  347. u'Hello\\\\u0020World !'
  348. The raw mode is most useful when you have to enter lots of backslashes, as can
  349. be necessary in regular expressions.
  350. Apart from these standard encodings, Python provides a whole set of other ways
  351. of creating Unicode strings on the basis of a known encoding.
  352. .. index:: builtin: unicode
  353. The built-in function :func:`unicode` provides access to all registered Unicode
  354. codecs (COders and DECoders). Some of the more well known encodings which these
  355. codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
  356. are variable-length encodings that store each Unicode character in one or more
  357. bytes. The default encoding is normally set to ASCII, which passes through
  358. characters in the range 0 to 127 and rejects any other characters with an error.
  359. When a Unicode string is printed, written to a file, or converted with
  360. :func:`str`, conversion takes place using this default encoding. ::
  361. >>> u"abc"
  362. u'abc'
  363. >>> str(u"abc")
  364. 'abc'
  365. >>> u"äöü"
  366. u'\xe4\xf6\xfc'
  367. >>> str(u"äöü")
  368. Traceback (most recent call last):
  369. File "<stdin>", line 1, in ?
  370. UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
  371. To convert a Unicode string into an 8-bit string using a specific encoding,
  372. Unicode objects provide an :func:`encode` method that takes one argument, the
  373. name of the encoding. Lowercase names for encodings are preferred. ::
  374. >>> u"äöü".encode('utf-8')
  375. '\xc3\xa4\xc3\xb6\xc3\xbc'
  376. If you have data in a specific encoding and want to produce a corresponding
  377. Unicode string from it, you can use the :func:`unicode` function with the
  378. encoding name as the second argument. ::
  379. >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
  380. u'\xe4\xf6\xfc'
  381. .. _tut-lists:
  382. Lists
  383. -----
  384. Python knows a number of *compound* data types, used to group together other
  385. values. The most versatile is the *list*, which can be written as a list of
  386. comma-separated values (items) between square brackets. List items need not all
  387. have the same type. ::
  388. >>> a = ['spam', 'eggs', 100, 1234]
  389. >>> a
  390. ['spam', 'eggs', 100, 1234]
  391. Like string indices, list indices start at 0, and lists can be sliced,
  392. concatenated and so on::
  393. >>> a[0]
  394. 'spam'
  395. >>> a[3]
  396. 1234
  397. >>> a[-2]
  398. 100
  399. >>> a[1:-1]
  400. ['eggs', 100]
  401. >>> a[:2] + ['bacon', 2*2]
  402. ['spam', 'eggs', 'bacon', 4]
  403. >>> 3*a[:3] + ['Boo!']
  404. ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
  405. Unlike strings, which are *immutable*, it is possible to change individual
  406. elements of a list::
  407. >>> a
  408. ['spam', 'eggs', 100, 1234]
  409. >>> a[2] = a[2] + 23
  410. >>> a
  411. ['spam', 'eggs', 123, 1234]
  412. Assignment to slices is also possible, and this can even change the size of the
  413. list or clear it entirely::
  414. >>> # Replace some items:
  415. ... a[0:2] = [1, 12]
  416. >>> a
  417. [1, 12, 123, 1234]
  418. >>> # Remove some:
  419. ... a[0:2] = []
  420. >>> a
  421. [123, 1234]
  422. >>> # Insert some:
  423. ... a[1:1] = ['bletch', 'xyzzy']
  424. >>> a
  425. [123, 'bletch', 'xyzzy', 1234]
  426. >>> # Insert (a copy of) itself at the beginning
  427. >>> a[:0] = a
  428. >>> a
  429. [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
  430. >>> # Clear the list: replace all items with an empty list
  431. >>> a[:] = []
  432. >>> a
  433. []
  434. The built-in function :func:`len` also applies to lists::
  435. >>> a = ['a', 'b', 'c', 'd']
  436. >>> len(a)
  437. 4
  438. It is possible to nest lists (create lists containing other lists), for
  439. example::
  440. >>> q = [2, 3]
  441. >>> p = [1, q, 4]
  442. >>> len(p)
  443. 3
  444. >>> p[1]
  445. [2, 3]
  446. >>> p[1][0]
  447. 2
  448. >>> p[1].append('xtra') # See section 5.1
  449. >>> p
  450. [1, [2, 3, 'xtra'], 4]
  451. >>> q
  452. [2, 3, 'xtra']
  453. Note that in the last example, ``p[1]`` and ``q`` really refer to the same
  454. object! We'll come back to *object semantics* later.
  455. .. _tut-firststeps:
  456. First Steps Towards Programming
  457. ===============================
  458. Of course, we can use Python for more complicated tasks than adding two and two
  459. together. For instance, we can write an initial sub-sequence of the *Fibonacci*
  460. series as follows::
  461. >>> # Fibonacci series:
  462. ... # the sum of two elements defines the next
  463. ... a, b = 0, 1
  464. >>> while b < 10:
  465. ... print b
  466. ... a, b = b, a+b
  467. ...
  468. 1
  469. 1
  470. 2
  471. 3
  472. 5
  473. 8
  474. This example introduces several new features.
  475. * The first line contains a *multiple assignment*: the variables ``a`` and ``b``
  476. simultaneously get the new values 0 and 1. On the last line this is used again,
  477. demonstrating that the expressions on the right-hand side are all evaluated
  478. first before any of the assignments take place. The right-hand side expressions
  479. are evaluated from the left to the right.
  480. * The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
  481. remains true. In Python, like in C, any non-zero integer value is true; zero is
  482. false. The condition may also be a string or list value, in fact any sequence;
  483. anything with a non-zero length is true, empty sequences are false. The test
  484. used in the example is a simple comparison. The standard comparison operators
  485. are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
  486. (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
  487. and ``!=`` (not equal to).
  488. * The *body* of the loop is *indented*: indentation is Python's way of grouping
  489. statements. Python does not (yet!) provide an intelligent input line editing
  490. facility, so you have to type a tab or space(s) for each indented line. In
  491. practice you will prepare more complicated input for Python with a text editor;
  492. most text editors have an auto-indent facility. When a compound statement is
  493. entered interactively, it must be followed by a blank line to indicate
  494. completion (since the parser cannot guess when you have typed the last line).
  495. Note that each line within a basic block must be indented by the same amount.
  496. * The :keyword:`print` statement writes the value of the expression(s) it is
  497. given. It differs from just writing the expression you want to write (as we did
  498. earlier in the calculator examples) in the way it handles multiple expressions
  499. and strings. Strings are printed without quotes, and a space is inserted
  500. between items, so you can format things nicely, like this::
  501. >>> i = 256*256
  502. >>> print 'The value of i is', i
  503. The value of i is 65536
  504. A trailing comma avoids the newline after the output::
  505. >>> a, b = 0, 1
  506. >>> while b < 1000:
  507. ... print b,
  508. ... a, b = b, a+b
  509. ...
  510. 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
  511. Note that the interpreter inserts a newline before it prints the next prompt if
  512. the last line was not completed.