Serhiy Storchaka | 410d77f | 2015-05-25 12:27:39 +0300 | [diff] [blame] | 1 | .. _tut-informal: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2 | |
| 3 | ********************************** |
| 4 | An Informal Introduction to Python |
| 5 | ********************************** |
| 6 | |
| 7 | In the following examples, input and output are distinguished by the presence or |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 8 | absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 25 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 47 | (for example, Pascal or C); parentheses (``()``) can be used for grouping. |
| 48 | For example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 50 | >>> 2 + 2 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | 4 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 52 | >>> 50 - 5*6 |
| 53 | 20 |
| 54 | >>> (50 - 5*6) / 4 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 55 | 5.0 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 56 | >>> 8 / 5 # division always returns a floating point number |
Mark Dickinson | 5a55b61 | 2009-06-28 20:59:42 +0000 | [diff] [blame] | 57 | 1.6 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 58 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 59 | The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`, |
| 60 | the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type |
Zachary Ware | 26d5fab | 2014-01-14 08:44:49 -0600 | [diff] [blame] | 61 | :class:`float`. We will see more about numeric types later in the tutorial. |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 62 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 63 | Division (``/``) always returns a float. To do :term:`floor division` and |
| 64 | get an integer result (discarding any fractional result) you can use the ``//`` |
| 65 | operator; to calculate the remainder you can use ``%``:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 66 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 67 | >>> 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 73 | 2 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 74 | >>> 5 * 3 + 2 # result * divisor + remainder |
| 75 | 17 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 | |
Zachary Ware | 2d130367 | 2014-01-14 08:40:53 -0600 | [diff] [blame] | 77 | With Python, it is possible to use the ``**`` operator to calculate powers [#]_:: |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 78 | |
| 79 | >>> 5 ** 2 # 5 squared |
| 80 | 25 |
| 81 | >>> 2 ** 7 # 2 to the power of 7 |
| 82 | 128 |
| 83 | |
| 84 | The equal sign (``=``) is used to assign a value to a variable. Afterwards, no |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 85 | result is displayed before the next interactive prompt:: |
| 86 | |
| 87 | >>> width = 20 |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 88 | >>> height = 5 * 9 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 89 | >>> width * height |
| 90 | 900 |
| 91 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 92 | If a variable is not "defined" (assigned a value), trying to use it will |
| 93 | give you an error:: |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 94 | |
Chris Jerdonek | 9bb56a6 | 2012-09-24 19:28:59 -0700 | [diff] [blame] | 95 | >>> n # try to access an undefined variable |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 96 | Traceback (most recent call last): |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 97 | File "<stdin>", line 1, in <module> |
| 98 | NameError: name 'n' is not defined |
| 99 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 100 | There is full support for floating point; operators with mixed type operands |
| 101 | convert 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 108 | In 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 |
| 110 | somewhat 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 120 | |
| 121 | This variable should be treated as read-only by the user. Don't explicitly |
| 122 | assign a value to it --- you would create an independent local variable with the |
| 123 | same name masking the built-in variable with its magic behavior. |
| 124 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 125 | In addition to :class:`int` and :class:`float`, Python supports other types of |
| 126 | numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`. |
| 127 | Python also has built-in support for :ref:`complex numbers <typesnumeric>`, |
| 128 | and uses the ``j`` or ``J`` suffix to indicate the imaginary part |
| 129 | (e.g. ``3+5j``). |
| 130 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 131 | |
| 132 | .. _tut-strings: |
| 133 | |
| 134 | Strings |
| 135 | ------- |
| 136 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 137 | Besides numbers, Python can also manipulate strings, which can be expressed |
| 138 | in several ways. They can be enclosed in single quotes (``'...'``) or |
| 139 | double quotes (``"..."``) with the same result [#]_. ``\`` can be used |
| 140 | to escape quotes:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 142 | >>> 'spam eggs' # single quotes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 143 | 'spam eggs' |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 144 | >>> 'doesn\'t' # use \' to escape the single quote... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 145 | "doesn't" |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 146 | >>> "doesn't" # ...or use double quotes instead |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 147 | "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 Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 155 | In the interactive interpreter, the output string is enclosed in quotes and |
| 156 | special characters are escaped with backslashes. While this might sometimes |
| 157 | look different from the input (the enclosing quotes could change), the two |
| 158 | strings are equivalent. The string is enclosed in double quotes if |
| 159 | the string contains a single quote and no double quotes, otherwise it is |
| 160 | enclosed in single quotes. The :func:`print` function produces a more |
| 161 | readable output, by omitting the enclosing quotes and by printing escaped |
| 162 | and special characters:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 163 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 164 | >>> '"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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 175 | If you don't want characters prefaced by ``\`` to be interpreted as |
| 176 | special characters, you can use *raw strings* by adding an ``r`` before |
| 177 | the first quote:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 178 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 179 | >>> 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 185 | String literals can span multiple lines. One way is using triple-quotes: |
| 186 | ``"""..."""`` or ``'''...'''``. End of lines are automatically |
| 187 | included in the string, but it's possible to prevent this by adding a ``\`` at |
| 188 | the end of the line. The following example:: |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 189 | |
Terry Reedy | 02a807e | 2010-11-12 04:22:22 +0000 | [diff] [blame] | 190 | print("""\ |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 191 | Usage: thingy [OPTIONS] |
| 192 | -h Display this usage message |
| 193 | -H hostname Hostname to connect to |
Ezio Melotti | b297e71 | 2009-09-25 20:14:02 +0000 | [diff] [blame] | 194 | """) |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 195 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 196 | produces the following output (note that the initial newline is not included): |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 197 | |
| 198 | .. code-block:: text |
| 199 | |
| 200 | Usage: thingy [OPTIONS] |
| 201 | -h Display this usage message |
| 202 | -H hostname Hostname to connect to |
| 203 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 204 | Strings can be concatenated (glued together) with the ``+`` operator, and |
| 205 | repeated with ``*``:: |
| 206 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 207 | >>> # 3 times 'un', followed by 'ium' |
| 208 | >>> 3 * 'un' + 'ium' |
| 209 | 'unununium' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 211 | Two or more *string literals* (i.e. the ones enclosed between quotes) next |
| 212 | to each other are automatically concatenated. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 213 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 214 | >>> 'Py' 'thon' |
| 215 | 'Python' |
| 216 | |
| 217 | This 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 225 | SyntaxError: invalid syntax |
| 226 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 227 | If you want to concatenate variables or a variable and a literal, use ``+``:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 229 | >>> prefix + 'thon' |
| 230 | 'Python' |
| 231 | |
| 232 | This feature is particularly useful when you want to break long strings:: |
| 233 | |
| 234 | >>> text = ('Put several strings within parentheses ' |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 235 | ... 'to have them joined together.') |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 236 | >>> text |
| 237 | 'Put several strings within parentheses to have them joined together.' |
| 238 | |
| 239 | Strings can be *indexed* (subscripted), with the first character having index 0. |
| 240 | There is no separate character type; a character is simply a string of size |
| 241 | one:: |
| 242 | |
| 243 | >>> word = 'Python' |
| 244 | >>> word[0] # character in position 0 |
| 245 | 'P' |
| 246 | >>> word[5] # character in position 5 |
| 247 | 'n' |
| 248 | |
| 249 | Indices 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 | |
| 258 | Note that since -0 is the same as 0, negative indices start from -1. |
| 259 | |
| 260 | In addition to indexing, *slicing* is also supported. While indexing is used |
| 261 | to 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 Melotti | 93dd693 | 2013-07-08 17:52:54 +0200 | [diff] [blame] | 265 | >>> word[2:5] # characters from position 2 (included) to 5 (excluded) |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 266 | 'tho' |
| 267 | |
| 268 | Note how the start is always included, and the end always excluded. This |
| 269 | makes 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 275 | |
| 276 | Slice indices have useful defaults; an omitted first index defaults to zero, an |
| 277 | omitted second index defaults to the size of the string being sliced. :: |
| 278 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 279 | >>> word[:2] # character from the beginning to position 2 (excluded) |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 280 | 'Py' |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 281 | >>> word[4:] # characters from position 4 (included) to the end |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 282 | 'on' |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 283 | >>> word[-2:] # characters from the second-last (included) to the end |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 284 | 'on' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 285 | |
| 286 | One 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. |
| 288 | Then the right edge of the last character of a string of *n* characters has |
| 289 | index *n*, for example:: |
| 290 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 291 | +---+---+---+---+---+---+ |
| 292 | | P | y | t | h | o | n | |
| 293 | +---+---+---+---+---+---+ |
| 294 | 0 1 2 3 4 5 6 |
| 295 | -6 -5 -4 -3 -2 -1 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 297 | The first row of numbers gives the position of the indices 0...6 in the string; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 298 | the 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*, |
| 300 | respectively. |
| 301 | |
| 302 | For non-negative indices, the length of a slice is the difference of the |
| 303 | indices, if both are within bounds. For example, the length of ``word[1:3]`` is |
| 304 | 2. |
| 305 | |
Martin Panter | 7462b649 | 2015-11-02 03:37:02 +0000 | [diff] [blame] | 306 | Attempting to use an index that is too large will result in an error:: |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 307 | |
Berker Peksag | 2338156 | 2014-12-17 14:56:47 +0200 | [diff] [blame] | 308 | >>> word[42] # the word only has 6 characters |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 309 | Traceback (most recent call last): |
| 310 | File "<stdin>", line 1, in <module> |
| 311 | IndexError: string index out of range |
| 312 | |
| 313 | However, out of range slice indexes are handled gracefully when used for |
| 314 | slicing:: |
| 315 | |
| 316 | >>> word[4:42] |
| 317 | 'on' |
| 318 | >>> word[42:] |
| 319 | '' |
| 320 | |
| 321 | Python strings cannot be changed --- they are :term:`immutable`. |
| 322 | Therefore, 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 | |
| 331 | If 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 338 | The 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 Melotti | a6229e6 | 2012-10-12 10:59:14 +0300 | [diff] [blame] | 347 | :ref:`textseq` |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 348 | Strings are examples of *sequence types*, and support the common |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 349 | operations supported by such types. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 350 | |
| 351 | :ref:`string-methods` |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 352 | Strings support a large number of methods for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 353 | basic transformations and searching. |
| 354 | |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 355 | :ref:`f-strings` |
| 356 | String literals that have embedded expressions. |
| 357 | |
Martin Panter | d5db147 | 2016-02-08 01:34:09 +0000 | [diff] [blame] | 358 | :ref:`formatstrings` |
| 359 | Information about string formatting with :meth:`str.format`. |
Benjamin Peterson | e6f0063 | 2008-05-26 01:03:56 +0000 | [diff] [blame] | 360 | |
| 361 | :ref:`old-string-formatting` |
| 362 | The old formatting operations invoked when strings and Unicode strings are |
| 363 | the left operand of the ``%`` operator are described in more detail here. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | |
| 365 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 366 | .. _tut-lists: |
| 367 | |
| 368 | Lists |
| 369 | ----- |
| 370 | |
| 371 | Python knows a number of *compound* data types, used to group together other |
| 372 | values. The most versatile is the *list*, which can be written as a list of |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 373 | comma-separated values (items) between square brackets. Lists might contain |
| 374 | items of different types, but usually the items all have the same type. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 376 | >>> squares = [1, 4, 9, 16, 25] |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 377 | >>> squares |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 378 | [1, 4, 9, 16, 25] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 379 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 380 | Like strings (and all other built-in :term:`sequence` type), lists can be |
| 381 | indexed and sliced:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 383 | >>> squares[0] # indexing returns the item |
| 384 | 1 |
| 385 | >>> squares[-1] |
| 386 | 25 |
| 387 | >>> squares[-3:] # slicing returns a new list |
| 388 | [9, 16, 25] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 389 | |
Benjamin Peterson | 886af96 | 2010-03-21 23:13:07 +0000 | [diff] [blame] | 390 | All slice operations return a new list containing the requested elements. This |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 391 | means that the following slice returns a new (shallow) copy of the list:: |
Benjamin Peterson | 886af96 | 2010-03-21 23:13:07 +0000 | [diff] [blame] | 392 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 393 | >>> squares[:] |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 394 | [1, 4, 9, 16, 25] |
Benjamin Peterson | 886af96 | 2010-03-21 23:13:07 +0000 | [diff] [blame] | 395 | |
Berker Peksag | b68c420 | 2015-01-27 02:52:14 +0200 | [diff] [blame] | 396 | Lists also support operations like concatenation:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 397 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 398 | >>> squares + [36, 49, 64, 81, 100] |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 399 | [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 400 | |
| 401 | Unlike strings, which are :term:`immutable`, lists are a :term:`mutable` |
| 402 | type, i.e. it is possible to change their content:: |
| 403 | |
| 404 | >>> cubes = [1, 8, 27, 65, 125] # something's wrong here |
| 405 | >>> 4 ** 3 # the cube of 4 is 64, not 65! |
| 406 | 64 |
| 407 | >>> cubes[3] = 64 # replace the wrong value |
| 408 | >>> cubes |
| 409 | [1, 8, 27, 64, 125] |
| 410 | |
| 411 | You can also add new items at the end of the list, by using |
| 412 | the :meth:`~list.append` *method* (we will see more about methods later):: |
| 413 | |
| 414 | >>> cubes.append(216) # add the cube of 6 |
| 415 | >>> cubes.append(7 ** 3) # and the cube of 7 |
| 416 | >>> cubes |
| 417 | [1, 8, 27, 64, 125, 216, 343] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 418 | |
| 419 | Assignment to slices is also possible, and this can even change the size of the |
| 420 | list or clear it entirely:: |
| 421 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 422 | >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] |
| 423 | >>> letters |
| 424 | ['a', 'b', 'c', 'd', 'e', 'f', 'g'] |
| 425 | >>> # replace some values |
| 426 | >>> letters[2:5] = ['C', 'D', 'E'] |
| 427 | >>> letters |
| 428 | ['a', 'b', 'C', 'D', 'E', 'f', 'g'] |
| 429 | >>> # now remove them |
| 430 | >>> letters[2:5] = [] |
| 431 | >>> letters |
| 432 | ['a', 'b', 'f', 'g'] |
| 433 | >>> # clear the list by replacing all the elements with an empty list |
| 434 | >>> letters[:] = [] |
| 435 | >>> letters |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 436 | [] |
| 437 | |
| 438 | The built-in function :func:`len` also applies to lists:: |
| 439 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 440 | >>> letters = ['a', 'b', 'c', 'd'] |
| 441 | >>> len(letters) |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 442 | 4 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 443 | |
| 444 | It is possible to nest lists (create lists containing other lists), for |
| 445 | example:: |
| 446 | |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 447 | >>> a = ['a', 'b', 'c'] |
| 448 | >>> n = [1, 2, 3] |
| 449 | >>> x = [a, n] |
| 450 | >>> x |
| 451 | [['a', 'b', 'c'], [1, 2, 3]] |
Serhiy Storchaka | fef952a | 2013-05-28 12:49:34 +0300 | [diff] [blame] | 452 | >>> x[0] |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 453 | ['a', 'b', 'c'] |
Serhiy Storchaka | fef952a | 2013-05-28 12:49:34 +0300 | [diff] [blame] | 454 | >>> x[0][1] |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 455 | 'b' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 456 | |
| 457 | .. _tut-firststeps: |
| 458 | |
| 459 | First Steps Towards Programming |
| 460 | =============================== |
| 461 | |
| 462 | Of course, we can use Python for more complicated tasks than adding two and two |
| 463 | together. For instance, we can write an initial sub-sequence of the *Fibonacci* |
| 464 | series as follows:: |
| 465 | |
| 466 | >>> # Fibonacci series: |
| 467 | ... # the sum of two elements defines the next |
| 468 | ... a, b = 0, 1 |
| 469 | >>> while b < 10: |
Georg Brandl | 22ec03c | 2008-01-07 17:32:13 +0000 | [diff] [blame] | 470 | ... print(b) |
| 471 | ... a, b = b, a+b |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 472 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 473 | 1 |
| 474 | 1 |
| 475 | 2 |
| 476 | 3 |
| 477 | 5 |
| 478 | 8 |
| 479 | |
| 480 | This example introduces several new features. |
| 481 | |
| 482 | * The first line contains a *multiple assignment*: the variables ``a`` and ``b`` |
| 483 | simultaneously get the new values 0 and 1. On the last line this is used again, |
| 484 | demonstrating that the expressions on the right-hand side are all evaluated |
| 485 | first before any of the assignments take place. The right-hand side expressions |
| 486 | are evaluated from the left to the right. |
| 487 | |
| 488 | * The :keyword:`while` loop executes as long as the condition (here: ``b < 10``) |
| 489 | remains true. In Python, like in C, any non-zero integer value is true; zero is |
| 490 | false. The condition may also be a string or list value, in fact any sequence; |
| 491 | anything with a non-zero length is true, empty sequences are false. The test |
| 492 | used in the example is a simple comparison. The standard comparison operators |
| 493 | are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==`` |
| 494 | (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to) |
| 495 | and ``!=`` (not equal to). |
| 496 | |
| 497 | * The *body* of the loop is *indented*: indentation is Python's way of grouping |
Georg Brandl | 1532c8f | 2011-12-25 19:03:07 +0100 | [diff] [blame] | 498 | statements. At the interactive prompt, you have to type a tab or space(s) for |
| 499 | each indented line. In practice you will prepare more complicated input |
| 500 | for Python with a text editor; all decent text editors have an auto-indent |
| 501 | facility. When a compound statement is entered interactively, it must be |
| 502 | followed by a blank line to indicate completion (since the parser cannot |
| 503 | guess when you have typed the last line). Note that each line within a basic |
| 504 | block must be indented by the same amount. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
Benjamin Peterson | 0781900 | 2013-01-20 10:05:13 -0500 | [diff] [blame] | 506 | * The :func:`print` function writes the value of the argument(s) it is given. |
| 507 | It differs from just writing the expression you want to write (as we did |
| 508 | earlier in the calculator examples) in the way it handles multiple arguments, |
| 509 | floating point quantities, and strings. Strings are printed without quotes, |
| 510 | and a space is inserted between items, so you can format things nicely, like |
| 511 | this:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 512 | |
| 513 | >>> i = 256*256 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 514 | >>> print('The value of i is', i) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 515 | The value of i is 65536 |
| 516 | |
Benjamin Peterson | 648fa19 | 2013-01-20 10:09:44 -0500 | [diff] [blame] | 517 | The keyword argument *end* can be used to avoid the newline after the output, |
| 518 | or end the output with a different string:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 519 | |
| 520 | >>> a, b = 0, 1 |
| 521 | >>> while b < 1000: |
Terry Reedy | 02a807e | 2010-11-12 04:22:22 +0000 | [diff] [blame] | 522 | ... print(b, end=',') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 523 | ... a, b = b, a+b |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 524 | ... |
Terry Reedy | 02a807e | 2010-11-12 04:22:22 +0000 | [diff] [blame] | 525 | 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, |
Ezio Melotti | 86aecc3 | 2013-05-20 08:12:32 +0300 | [diff] [blame] | 526 | |
| 527 | |
| 528 | .. rubric:: Footnotes |
| 529 | |
| 530 | .. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be |
| 531 | interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this |
| 532 | and get ``9``, you can use ``(-3)**2``. |
| 533 | |
| 534 | .. [#] Unlike other languages, special characters such as ``\n`` have the |
| 535 | same meaning with both single (``'...'``) and double (``"..."``) quotes. |
| 536 | The only difference between the two is that within single quotes you don't |
| 537 | need to escape ``"`` (but you have to escape ``\'``) and vice versa. |