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