1.. _tut-informal: 2 3********************************** 4An Informal Introduction to Python 5********************************** 6 7In the following examples, input and output are distinguished by the presence or 8absence of prompts (:term:`>>>` and :term:`...`): 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 14.. only:: html 15 16 You can toggle the display of prompts and output by clicking on ``>>>`` 17 in the upper-right corner of an example box. If you hide the prompts 18 and output for an example, then you can easily copy and paste the input 19 lines into your interpreter. 20 21.. index:: single: # (hash); comment 22 23Many of the examples in this manual, even those entered at the interactive 24prompt, include comments. Comments in Python start with the hash character, 25``#``, and extend to the end of the physical line. A comment may appear at the 26start of a line or following whitespace or code, but not within a string 27literal. A hash character within a string literal is just a hash character. 28Since comments are to clarify code and are not interpreted by Python, they may 29be omitted when typing in examples. 30 31Some examples:: 32 33 # this is the first comment 34 spam = 1 # and this is the second comment 35 # ... and now a third! 36 text = "# This is not a comment because it's inside quotes." 37 38 39.. _tut-calculator: 40 41Using Python as a Calculator 42============================ 43 44Let's try some simple Python commands. Start the interpreter and wait for the 45primary prompt, ``>>>``. (It shouldn't take long.) 46 47 48.. _tut-numbers: 49 50Numbers 51------- 52 53The interpreter acts as a simple calculator: you can type an expression at it 54and it will write the value. Expression syntax is straightforward: the 55operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages 56(for example, Pascal or C); parentheses (``()``) can be used for grouping. 57For example:: 58 59 >>> 2 + 2 60 4 61 >>> 50 - 5*6 62 20 63 >>> (50 - 5*6) / 4 64 5.0 65 >>> 8 / 5 # division always returns a floating point number 66 1.6 67 68The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`, 69the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type 70:class:`float`. We will see more about numeric types later in the tutorial. 71 72Division (``/``) always returns a float. To do :term:`floor division` and 73get an integer result you can use the ``//`` operator; to calculate 74the remainder you can use ``%``:: 75 76 >>> 17 / 3 # classic division returns a float 77 5.666666666666667 78 >>> 79 >>> 17 // 3 # floor division discards the fractional part 80 5 81 >>> 17 % 3 # the % operator returns the remainder of the division 82 2 83 >>> 5 * 3 + 2 # floored quotient * divisor + remainder 84 17 85 86With Python, it is possible to use the ``**`` operator to calculate powers [#]_:: 87 88 >>> 5 ** 2 # 5 squared 89 25 90 >>> 2 ** 7 # 2 to the power of 7 91 128 92 93The equal sign (``=``) is used to assign a value to a variable. Afterwards, no 94result is displayed before the next interactive prompt:: 95 96 >>> width = 20 97 >>> height = 5 * 9 98 >>> width * height 99 900 100 101If a variable is not "defined" (assigned a value), trying to use it will 102give you an error:: 103 104 >>> n # try to access an undefined variable 105 Traceback (most recent call last): 106 File "<stdin>", line 1, in <module> 107 NameError: name 'n' is not defined 108 109There is full support for floating point; operators with mixed type operands 110convert the integer operand to floating point:: 111 112 >>> 4 * 3.75 - 1 113 14.0 114 115In interactive mode, the last printed expression is assigned to the variable 116``_``. This means that when you are using Python as a desk calculator, it is 117somewhat easier to continue calculations, for example:: 118 119 >>> tax = 12.5 / 100 120 >>> price = 100.50 121 >>> price * tax 122 12.5625 123 >>> price + _ 124 113.0625 125 >>> round(_, 2) 126 113.06 127 128This variable should be treated as read-only by the user. Don't explicitly 129assign a value to it --- you would create an independent local variable with the 130same name masking the built-in variable with its magic behavior. 131 132In addition to :class:`int` and :class:`float`, Python supports other types of 133numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`. 134Python also has built-in support for :ref:`complex numbers <typesnumeric>`, 135and uses the ``j`` or ``J`` suffix to indicate the imaginary part 136(e.g. ``3+5j``). 137 138 139.. _tut-strings: 140 141Strings 142------- 143 144Besides numbers, Python can also manipulate strings, which can be expressed 145in several ways. They can be enclosed in single quotes (``'...'``) or 146double quotes (``"..."``) with the same result [#]_. ``\`` can be used 147to escape quotes:: 148 149 >>> 'spam eggs' # single quotes 150 'spam eggs' 151 >>> 'doesn\'t' # use \' to escape the single quote... 152 "doesn't" 153 >>> "doesn't" # ...or use double quotes instead 154 "doesn't" 155 >>> '"Yes," they said.' 156 '"Yes," they said.' 157 >>> "\"Yes,\" they said." 158 '"Yes," they said.' 159 >>> '"Isn\'t," they said.' 160 '"Isn\'t," they said.' 161 162In the interactive interpreter, the output string is enclosed in quotes and 163special characters are escaped with backslashes. While this might sometimes 164look different from the input (the enclosing quotes could change), the two 165strings are equivalent. The string is enclosed in double quotes if 166the string contains a single quote and no double quotes, otherwise it is 167enclosed in single quotes. The :func:`print` function produces a more 168readable output, by omitting the enclosing quotes and by printing escaped 169and special characters:: 170 171 >>> '"Isn\'t," they said.' 172 '"Isn\'t," they said.' 173 >>> print('"Isn\'t," they said.') 174 "Isn't," they said. 175 >>> s = 'First line.\nSecond line.' # \n means newline 176 >>> s # without print(), \n is included in the output 177 'First line.\nSecond line.' 178 >>> print(s) # with print(), \n produces a new line 179 First line. 180 Second line. 181 182If you don't want characters prefaced by ``\`` to be interpreted as 183special characters, you can use *raw strings* by adding an ``r`` before 184the first quote:: 185 186 >>> print('C:\some\name') # here \n means newline! 187 C:\some 188 ame 189 >>> print(r'C:\some\name') # note the r before the quote 190 C:\some\name 191 192There is one subtle aspect to raw strings: a raw string may not end in 193an odd number of ``\`` characters; see 194:ref:`the FAQ entry <faq-programming-raw-string-backslash>` for more information 195and workarounds. 196 197String literals can span multiple lines. One way is using triple-quotes: 198``"""..."""`` or ``'''...'''``. End of lines are automatically 199included in the string, but it's possible to prevent this by adding a ``\`` at 200the end of the line. The following example:: 201 202 print("""\ 203 Usage: thingy [OPTIONS] 204 -h Display this usage message 205 -H hostname Hostname to connect to 206 """) 207 208produces the following output (note that the initial newline is not included): 209 210.. code-block:: text 211 212 Usage: thingy [OPTIONS] 213 -h Display this usage message 214 -H hostname Hostname to connect to 215 216Strings can be concatenated (glued together) with the ``+`` operator, and 217repeated with ``*``:: 218 219 >>> # 3 times 'un', followed by 'ium' 220 >>> 3 * 'un' + 'ium' 221 'unununium' 222 223Two or more *string literals* (i.e. the ones enclosed between quotes) next 224to each other are automatically concatenated. :: 225 226 >>> 'Py' 'thon' 227 'Python' 228 229This feature is particularly useful when you want to break long strings:: 230 231 >>> text = ('Put several strings within parentheses ' 232 ... 'to have them joined together.') 233 >>> text 234 'Put several strings within parentheses to have them joined together.' 235 236This only works with two literals though, not with variables or expressions:: 237 238 >>> prefix = 'Py' 239 >>> prefix 'thon' # can't concatenate a variable and a string literal 240 File "<stdin>", line 1 241 prefix 'thon' 242 ^^^^^^ 243 SyntaxError: invalid syntax 244 >>> ('un' * 3) 'ium' 245 File "<stdin>", line 1 246 ('un' * 3) 'ium' 247 ^^^^^ 248 SyntaxError: invalid syntax 249 250If you want to concatenate variables or a variable and a literal, use ``+``:: 251 252 >>> prefix + 'thon' 253 'Python' 254 255Strings can be *indexed* (subscripted), with the first character having index 0. 256There is no separate character type; a character is simply a string of size 257one:: 258 259 >>> word = 'Python' 260 >>> word[0] # character in position 0 261 'P' 262 >>> word[5] # character in position 5 263 'n' 264 265Indices may also be negative numbers, to start counting from the right:: 266 267 >>> word[-1] # last character 268 'n' 269 >>> word[-2] # second-last character 270 'o' 271 >>> word[-6] 272 'P' 273 274Note that since -0 is the same as 0, negative indices start from -1. 275 276In addition to indexing, *slicing* is also supported. While indexing is used 277to obtain individual characters, *slicing* allows you to obtain substring:: 278 279 >>> word[0:2] # characters from position 0 (included) to 2 (excluded) 280 'Py' 281 >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 282 'tho' 283 284Slice indices have useful defaults; an omitted first index defaults to zero, an 285omitted second index defaults to the size of the string being sliced. :: 286 287 >>> word[:2] # character from the beginning to position 2 (excluded) 288 'Py' 289 >>> word[4:] # characters from position 4 (included) to the end 290 'on' 291 >>> word[-2:] # characters from the second-last (included) to the end 292 'on' 293 294Note how the start is always included, and the end always excluded. This 295makes sure that ``s[:i] + s[i:]`` is always equal to ``s``:: 296 297 >>> word[:2] + word[2:] 298 'Python' 299 >>> word[:4] + word[4:] 300 'Python' 301 302One way to remember how slices work is to think of the indices as pointing 303*between* characters, with the left edge of the first character numbered 0. 304Then the right edge of the last character of a string of *n* characters has 305index *n*, for example:: 306 307 +---+---+---+---+---+---+ 308 | P | y | t | h | o | n | 309 +---+---+---+---+---+---+ 310 0 1 2 3 4 5 6 311 -6 -5 -4 -3 -2 -1 312 313The first row of numbers gives the position of the indices 0...6 in the string; 314the second row gives the corresponding negative indices. The slice from *i* to 315*j* consists of all characters between the edges labeled *i* and *j*, 316respectively. 317 318For non-negative indices, the length of a slice is the difference of the 319indices, if both are within bounds. For example, the length of ``word[1:3]`` is 3202. 321 322Attempting to use an index that is too large will result in an error:: 323 324 >>> word[42] # the word only has 6 characters 325 Traceback (most recent call last): 326 File "<stdin>", line 1, in <module> 327 IndexError: string index out of range 328 329However, out of range slice indexes are handled gracefully when used for 330slicing:: 331 332 >>> word[4:42] 333 'on' 334 >>> word[42:] 335 '' 336 337Python strings cannot be changed --- they are :term:`immutable`. 338Therefore, assigning to an indexed position in the string results in an error:: 339 340 >>> word[0] = 'J' 341 Traceback (most recent call last): 342 File "<stdin>", line 1, in <module> 343 TypeError: 'str' object does not support item assignment 344 >>> word[2:] = 'py' 345 Traceback (most recent call last): 346 File "<stdin>", line 1, in <module> 347 TypeError: 'str' object does not support item assignment 348 349If you need a different string, you should create a new one:: 350 351 >>> 'J' + word[1:] 352 'Jython' 353 >>> word[:2] + 'py' 354 'Pypy' 355 356The built-in function :func:`len` returns the length of a string:: 357 358 >>> s = 'supercalifragilisticexpialidocious' 359 >>> len(s) 360 34 361 362 363.. seealso:: 364 365 :ref:`textseq` 366 Strings are examples of *sequence types*, and support the common 367 operations supported by such types. 368 369 :ref:`string-methods` 370 Strings support a large number of methods for 371 basic transformations and searching. 372 373 :ref:`f-strings` 374 String literals that have embedded expressions. 375 376 :ref:`formatstrings` 377 Information about string formatting with :meth:`str.format`. 378 379 :ref:`old-string-formatting` 380 The old formatting operations invoked when strings are 381 the left operand of the ``%`` operator are described in more detail here. 382 383 384.. _tut-lists: 385 386Lists 387----- 388 389Python knows a number of *compound* data types, used to group together other 390values. The most versatile is the *list*, which can be written as a list of 391comma-separated values (items) between square brackets. Lists might contain 392items of different types, but usually the items all have the same type. :: 393 394 >>> squares = [1, 4, 9, 16, 25] 395 >>> squares 396 [1, 4, 9, 16, 25] 397 398Like strings (and all other built-in :term:`sequence` types), lists can be 399indexed and sliced:: 400 401 >>> squares[0] # indexing returns the item 402 1 403 >>> squares[-1] 404 25 405 >>> squares[-3:] # slicing returns a new list 406 [9, 16, 25] 407 408All slice operations return a new list containing the requested elements. This 409means that the following slice returns a 410:ref:`shallow copy <shallow_vs_deep_copy>` of the list:: 411 412 >>> squares[:] 413 [1, 4, 9, 16, 25] 414 415Lists also support operations like concatenation:: 416 417 >>> squares + [36, 49, 64, 81, 100] 418 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 419 420Unlike strings, which are :term:`immutable`, lists are a :term:`mutable` 421type, i.e. it is possible to change their content:: 422 423 >>> cubes = [1, 8, 27, 65, 125] # something's wrong here 424 >>> 4 ** 3 # the cube of 4 is 64, not 65! 425 64 426 >>> cubes[3] = 64 # replace the wrong value 427 >>> cubes 428 [1, 8, 27, 64, 125] 429 430You can also add new items at the end of the list, by using 431the :meth:`~list.append` *method* (we will see more about methods later):: 432 433 >>> cubes.append(216) # add the cube of 6 434 >>> cubes.append(7 ** 3) # and the cube of 7 435 >>> cubes 436 [1, 8, 27, 64, 125, 216, 343] 437 438Assignment to slices is also possible, and this can even change the size of the 439list or clear it entirely:: 440 441 >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 442 >>> letters 443 ['a', 'b', 'c', 'd', 'e', 'f', 'g'] 444 >>> # replace some values 445 >>> letters[2:5] = ['C', 'D', 'E'] 446 >>> letters 447 ['a', 'b', 'C', 'D', 'E', 'f', 'g'] 448 >>> # now remove them 449 >>> letters[2:5] = [] 450 >>> letters 451 ['a', 'b', 'f', 'g'] 452 >>> # clear the list by replacing all the elements with an empty list 453 >>> letters[:] = [] 454 >>> letters 455 [] 456 457The built-in function :func:`len` also applies to lists:: 458 459 >>> letters = ['a', 'b', 'c', 'd'] 460 >>> len(letters) 461 4 462 463It is possible to nest lists (create lists containing other lists), for 464example:: 465 466 >>> a = ['a', 'b', 'c'] 467 >>> n = [1, 2, 3] 468 >>> x = [a, n] 469 >>> x 470 [['a', 'b', 'c'], [1, 2, 3]] 471 >>> x[0] 472 ['a', 'b', 'c'] 473 >>> x[0][1] 474 'b' 475 476.. _tut-firststeps: 477 478First Steps Towards Programming 479=============================== 480 481Of course, we can use Python for more complicated tasks than adding two and two 482together. For instance, we can write an initial sub-sequence of the 483`Fibonacci series <https://en.wikipedia.org/wiki/Fibonacci_number>`_ 484as follows:: 485 486 >>> # Fibonacci series: 487 ... # the sum of two elements defines the next 488 ... a, b = 0, 1 489 >>> while a < 10: 490 ... print(a) 491 ... a, b = b, a+b 492 ... 493 0 494 1 495 1 496 2 497 3 498 5 499 8 500 501This example introduces several new features. 502 503* The first line contains a *multiple assignment*: the variables ``a`` and ``b`` 504 simultaneously get the new values 0 and 1. On the last line this is used again, 505 demonstrating that the expressions on the right-hand side are all evaluated 506 first before any of the assignments take place. The right-hand side expressions 507 are evaluated from the left to the right. 508 509* The :keyword:`while` loop executes as long as the condition (here: ``a < 10``) 510 remains true. In Python, like in C, any non-zero integer value is true; zero is 511 false. The condition may also be a string or list value, in fact any sequence; 512 anything with a non-zero length is true, empty sequences are false. The test 513 used in the example is a simple comparison. The standard comparison operators 514 are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==`` 515 (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to) 516 and ``!=`` (not equal to). 517 518* The *body* of the loop is *indented*: indentation is Python's way of grouping 519 statements. At the interactive prompt, you have to type a tab or space(s) for 520 each indented line. In practice you will prepare more complicated input 521 for Python with a text editor; all decent text editors have an auto-indent 522 facility. When a compound statement is entered interactively, it must be 523 followed by a blank line to indicate completion (since the parser cannot 524 guess when you have typed the last line). Note that each line within a basic 525 block must be indented by the same amount. 526 527* The :func:`print` function writes the value of the argument(s) it is given. 528 It differs from just writing the expression you want to write (as we did 529 earlier in the calculator examples) in the way it handles multiple arguments, 530 floating point quantities, and strings. Strings are printed without quotes, 531 and a space is inserted between items, so you can format things nicely, like 532 this:: 533 534 >>> i = 256*256 535 >>> print('The value of i is', i) 536 The value of i is 65536 537 538 The keyword argument *end* can be used to avoid the newline after the output, 539 or end the output with a different string:: 540 541 >>> a, b = 0, 1 542 >>> while a < 1000: 543 ... print(a, end=',') 544 ... a, b = b, a+b 545 ... 546 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987, 547 548 549.. rubric:: Footnotes 550 551.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be 552 interpreted as ``-(3**2)`` and thus result in ``-9``. To avoid this 553 and get ``9``, you can use ``(-3)**2``. 554 555.. [#] Unlike other languages, special characters such as ``\n`` have the 556 same meaning with both single (``'...'``) and double (``"..."``) quotes. 557 The only difference between the two is that within single quotes you don't 558 need to escape ``"`` (but you have to escape ``\'``) and vice versa. 559