1_GettingStarted.ipynb 33.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Python Programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 1. Getting Started"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Running Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python itself normally exists just to run programs that you have written, but it can run as a program in its own right, allowing you to explore the language by typing commands which it then executes for you.  Quite a lot can be done at this command prompt, but to do anything serious you will need to start creating your programs in a text editor and executing them with Python.  However, we will start by looking at what you can do at the Python prompt."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
37
    "When you install Anaconda, it creates a program group containing a few different items. Included in this an interactive python console, 'jupyter qtconsole', which you should launch and use as your Python Shell (don't worry if you don't know what a shell is at this stage!). A second item, 'spyder', is a powerful text editor with the capacity to run your Python scripts in a dedicated shell window. You should launch this and use it when you start writing multi-line code that you will want to go back and edit/append as you go through the course."
38 39 40 41 42 43 44 45 46 47 48
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Below is an example of the IPython QtConsole window. Yours might look slightly different from this, depending on the operating system that you are working in, but the functionality of the program itself remains (almost) exactly the same."
   ]
  },
  {
   "cell_type": "markdown",
49 50 51
   "metadata": {
    "width": 50
   },
52
   "source": [
53
    "![An example of the Jupyter-Qtshell window](images/JupyterConsole.png)"
54 55 56 57 58 59
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
60
    "If you are running Linux or Mac OS X, start a terminal, type `ipython` and press return to get the same program within the terminal window. (To leave the shell, type `exit()` and press enter.)"
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this first worksheet, you can choose either to run the commands in the Python Shell or, if you are viewing this notebook interactively, you can execute your commands directly within the notebook code cells. We have inserted cells especially for you to play around with the code in. If you use these cells, you can execute the code within them with `CTRL+ENTER` and the output will be printed beneath the cell. Don't worry if you can't use this notebook interactively - you should just type all of the commands in the shell instead."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the window image above, the `In[1]` is the Python prompt and it should have a flashing cursor.  As is traditional under these circumstances, the first thing you should do is get Python to print out the text “Hello, World”. To do this, type the command below at the prompt and press return (control+return in the notebook)."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
79
   "execution_count": null,
80 81 82 83
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
Toby Hodges's avatar
Toby Hodges committed
84
   "outputs": [],
85 86 87 88 89 90
   "source": [
    "print('Hello, World')"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
91
   "execution_count": null,
92
   "metadata": {
93
    "collapsed": false
94 95 96
   },
   "outputs": [],
   "source": [
97
    "print('hello, world')"
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Barring the odd typing mistake you have just run your first Python script.  Here, 'print' is a Python function that tells the interpreter that you want it to output the things which follow in the brackets.  The 'Hello, World' is a _string_ and is what you want the `print` function to print out."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Playing with Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Python Shell is a great way to experiment with Python.  It’s something that I return to every time I find myself thinking “I wonder what happens if you do this?” or “What’s the best way to do that?”.  You can’t break anything by trying something out and if you do make a mistake, at least you will get an error message that you might be able to decode. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you are viewing this notebook interactively (i.e. not through nbviewer), the code cells behave in a very similar way to the Shell prompt. You can play around with Python in the notebook's code cells (we have left some blank ones for you to try out your own commands in) and execute the cell once you are done typing. The output of your commands will appear underneath. If you have made a mistake, or you want to try something else, you can edit the code in the cell and execute it again when you're done."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You are not limited in what you can do at the prompt.  You can load modules, look at them to see what they do, play with them.  The first versions of the bar charts in Worksheet 3 were all produced at the python prompt, which enabled me to tweak them before writing the program to produce the whole figure.  This meant I could see how they looked after every command and get them looking just as I wanted.  I could also check the documentation for the modules I wanted to use by typing `help()`.  There is a lot of information in there and you will find yourself using it again and again."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to these features of the Python Shell, the IPython Shell has some very helpful features that can make things easier while you learn the basics of Python. For example, IPython enables tab-completion for e.g. variable, function, and file names, gives hints about required & optional arguments for functions, and has improved command history interaction."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For longer, multi-line programs you will probably find it easier to use a text editor, and we will cover that in Worksheet 2."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Evaluating Expressions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Python shell can also be used to evaluate expressions, allowing you either to perform calculations interactively, or more usually to check more complicated expressions interactively before putting them in your programs.  The Python shell allows you to do all of the normal operations, in pretty much the way you would expect."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Have a go with some expressions, such as: "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
172
   "execution_count": null,
173 174 175 176
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
Toby Hodges's avatar
Toby Hodges committed
177
   "outputs": [],
178 179 180 181 182 183
   "source": [
    "3 * 4     # Multiplication"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
184
   "execution_count": null,
185 186 187 188 189 190 191 192 193 194
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
195
   "execution_count": null,
196 197 198
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
199
   "outputs": [],
200 201 202 203 204 205
   "source": [
    "7 + 10    # Addition"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
206
   "execution_count": null,
207 208 209 210 211 212 213 214 215 216
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
217
   "execution_count": null,
218 219 220
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
221
   "outputs": [],
222 223 224 225 226 227
   "source": [
    "7 - 10    # Subtraction "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
228
   "execution_count": null,
229 230 231 232 233 234 235 236 237 238
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
239
   "execution_count": null,
240 241 242
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
243
   "outputs": [],
244
   "source": [
245
    "10 / 3    # Division"
246 247 248 249
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
250
   "execution_count": null,
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far, so good, but don’t limit yourself to the examples here.  Try some of your own and make sure you understand the results.  There are a few other operators, though, which you might not be as familiar with.  Try these:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
268
   "execution_count": null,
269 270 271
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
272
   "outputs": [],
273 274 275 276 277 278
   "source": [
    "10 % 3     # Modulus (remainder)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
279
   "execution_count": null,
280 281 282 283 284 285 286 287 288 289
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
290
   "execution_count": null,
291 292 293
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
294
   "outputs": [],
295 296 297 298 299 300
   "source": [
    "2 ** 10    # Exponentiation (2 to the power of 10)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
301
   "execution_count": null,
302 303 304 305 306 307 308 309 310 311 312 313
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
314
    "Again, as expected.  However, there are a few things that you need to be aware of when using arithmetic in any programming language.  In Python v2.x, if your numbers are integers, Python with return an _integer_ value.  So try: "
315 316 317 318
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
319
   "execution_count": null,
320 321 322
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
323
   "outputs": [],
324 325 326 327 328 329
   "source": [
    "10 / 7"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
330
   "execution_count": null,
331 332 333 334 335 336 337 338 339 340 341 342
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
343
    "Here you should get the answer 1.4285714285714286 if you're using Python v3.x, or 1 if you're using Python 2.x. This is because Python 2.x returns an integer value if division is done with two integers, which in this case is the result of the division ignoring any decimal values (_i.e._ \"floor division\"). This has been changed in Python 3.x., and 10/7 now gives the result you most likely expect. Of course, you might actually only want the integer result in the first place, and regardless of the version you can force Python to give you that as well using so-called “floor division”:"
344 345 346 347
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
348
   "execution_count": null,
349 350 351
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
352
   "outputs": [],
353 354 355 356 357 358
   "source": [
    "10.0 // 7"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
359
   "execution_count": null,
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python can handle some very large numbers. For example, it can easily deal with raising 2 to the power of 32:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
377
   "execution_count": null,
378 379 380
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
381
   "outputs": [],
382 383 384 385 386 387 388 389 390 391 392 393 394
   "source": [
    "2 ** 32 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python can deal with numbers slightly larger than this too, so"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
395
   "execution_count": null,
396 397 398
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
399
   "outputs": [],
400 401 402 403 404 405 406 407 408 409 410 411 412
   "source": [
    "2 ** 64"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and even"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
413
   "execution_count": null,
414 415 416
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
417
   "outputs": [],
418 419 420 421 422 423 424 425 426 427 428 429 430
   "source": [
    "2 ** 1024"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "work just fine. You can go even higher, so raising to the power of 100,000"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
431
   "execution_count": null,
432 433 434
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
435
   "outputs": [],
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
   "source": [
    "2 ** 100000"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "is quite OK. Though I must admit that I haven’t actually checked that the 30103 digits of this result are correct."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some of these operators don’t just work on numbers, `+` and `*` can be used on strings as well.  Strings are just sequences of characters enclosed in quotation marks like the 'Hello, World' above.  Python doesn’t mind if you use single or double quotes as long as you don’t mix them.  \"Addition\", `+`, concatenates two (or more) strings together to return a new longer string.  \"Multiplication\", actually repetition, `*`, takes a number and a string and repeats the string that many times in a new string: "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
456
   "execution_count": null,
457 458 459
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
460
   "outputs": [],
461 462 463 464 465 466
   "source": [
    "'Hello, ' + \"world!\" "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
467
   "execution_count": null,
468 469 470 471 472 473 474 475 476 477
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
478
   "execution_count": null,
479 480 481
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
482
   "outputs": [],
483 484 485 486 487 488
   "source": [
    "'Hello ' * 8 "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
489
   "execution_count": null,
490 491 492 493 494 495 496 497 498 499
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
500
   "execution_count": null,
501 502 503
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
504
   "outputs": [],
505 506 507 508 509 510
   "source": [
    "9 * 'Hello...'"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
511
   "execution_count": null,
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### _Exercise 1.1_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
    "Try to use expressions that you would use in your normal work and see if they give the results you expect.  Explore using brackets to group sub-expressions (things in brackets are always evaluated before everything else).  Before you move on to the next section, which of the following expressions would correctly calculate the hypotenuse of a right-angled triangle, with sides length 12 and 5?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "a)\n",
    "```Python\n",
    "(12*2 + 5*2)/2\n",
    "```\n",
    "b)\n",
    "```Python\n",
    "(12**2 + 5**2)**0.5\n",
    "```\n",
    "c)\n",
    "```Python\n",
    "(12^2 + 5^2)^0.5\n",
    "```"
550 551 552 553
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
554
   "execution_count": null,
555
   "metadata": {
556
    "collapsed": false
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Using Variables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far, we have just been playing with what Python calls values.  When you are writing programs, it’s useful to be able to give names to the values that we are dealing with so that once we do a calculation or string manipulation we can refer to the results later.  We do this with an assignment statement, which looks like this:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
579
   "execution_count": null,
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You’ll notice that, when this line is executed, Python doesn’t return anything. This is also true if you capture the result of one of the expressions that we tried above:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
597
   "execution_count": null,
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "y = 10.0 / 7"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To look at the values, just type the names of the variables that you have created:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
615
   "execution_count": null,
616 617 618
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
619
   "outputs": [],
620 621 622 623 624 625
   "source": [
    "x"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
626
   "execution_count": null,
627 628 629
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
630
   "outputs": [],
631 632 633 634 635 636 637 638
   "source": [
    "y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
639
    "More normally, you would probably output the results using the `print` statement we started with:"
640 641 642 643
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
644
   "execution_count": null,
645 646 647
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
648
   "outputs": [],
649
   "source": [
650
    "print(x, y)"
651 652 653 654 655 656
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
657
    "If you are using Python 2.x you would use `print x, y` (without brackets), another one of the major differences between Python 2.x and Python 3.x."
658 659 660 661 662 663
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
664
    "If the brackets are included in the output above, then you're working in version 2. If not, then you have a version 3 environment. (Whichever version you have, you will be able to work through the rest of this course.)"
665 666 667 668 669 670 671 672 673 674 675
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As well as being on the left of an assignment operation, variable names can be used in the expressions as well, so"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
676
   "execution_count": null,
677 678 679 680 681 682 683 684 685 686 687 688
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = x + y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
689
    "replaces the value currently referred to by `x` with the new value obtained from adding the values of `x` and `y`."
690 691 692 693
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
694
   "execution_count": null,
695 696 697
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
698
   "outputs": [],
699 700 701 702 703 704 705 706 707 708 709 710 711
   "source": [
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Variables that refer to numbers are fine and are incredibly useful, but they are also one of the less interesting types of Python data.  This is because they only have a value.  Some variables are much more interesting, and string variables are a good example.  To assign a string to a variable you follow the same basic syntax as before:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
712
   "execution_count": null,
713 714 715 716 717 718 719 720 721 722
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "s = 'The quick brown fox jumps over the lazy dog'"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
723
   "execution_count": null,
724 725 726
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
727
   "outputs": [],
728
   "source": [
Toby Hodges's avatar
Toby Hodges committed
729
    "print(s)"
730 731 732 733 734 735 736 737 738 739 740
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, you can just type the variable name or use it in a `print` statement, but what makes a variable containing a string more interesting is that it is one of Python’s object data types.  This means that it doesn’t just passively hold the value of the string, it also knows about things you can do to the string.  For example:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
741
   "execution_count": null,
742 743 744
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
745
   "outputs": [],
746 747 748 749 750 751 752 753
   "source": [
    "s.upper()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
754
    "The `.` here indicates that the method is part of the string `s`, and the brackets indicate that we want to execute it. Here the brackets are empty, but later we will be using them to pass information into the methods.  There are many things that strings can do with themselves, and if you look at the Python cheat sheet, you will see what they all are. Try using them on the string, for example: "
755 756 757 758
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
759
   "execution_count": null,
760 761 762
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
763
   "outputs": [],
764 765 766 767 768 769
   "source": [
    "s.capitalize()"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
770
   "execution_count": null,
771 772 773
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
774
   "outputs": [],
775 776 777 778 779 780 781 782
   "source": [
    "s.title()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
783
    "If you look at `s` itself after any of these, you’ll see it hasn’t changed, these object methods simply return a new version of the string with the appropriate transformation done to it which you can then store in another variable (or back in `s`) if you want to.  This is because a string cannot be changed in place (in technical terms, it is _immutable_), only explicitly overwritten with a new value. So, to save the new version of the string, you can type the following:"
784 785 786 787
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
788
   "execution_count": null,
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "s = s.title()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use almost any combination of letters and numbers in the variable names, but you can’t start a variable name with a number. You can’t include spaces (a space is one of the ways that Python can tell that the name is finished) but you can include underscore characters.  Variable names can also begin with underscore, but these tend to be used under special circumstance which you will discover once you start learning about object-oriented programming."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### _Exercise 1.2_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use the .count() method on the string “The quick brown fox jumps over the lazy dog” to count the occurrences of the word “the”."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
820
   "execution_count": null,
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "s = \"The quick brown fox jumps over the lazy dog\" \n",
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If this returns 1, how could you persuade it that it should be 2?"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
839
   "execution_count": null,
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once you have that sorted out, try"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`s.split()`"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
864
   "execution_count": null,
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and see if you can understand what it has done."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Lists "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last exercise returned a result which you might think looks unusual.  My interpreter gave me:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
896
   "execution_count": null,
897 898 899
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
900
   "outputs": [],
901 902 903 904 905 906 907 908 909 910 911 912 913 914
   "source": [
    "s = \"The quick brown fox jumps over the lazy dog\"\n",
    "s.split()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This result is in the form of a _list_ object.  A list is exactly what you might expect based on the name.  It’s a set of values (which can be numbers, strings, objects or even lists, but that is a bit advanced for now) that are kept in a specific order.  You can create a new list using the same format as the result above:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
915
   "execution_count": null,
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "shopping = ['bread', 'potatoes', 'eggs', 'flour', 'rubber duck', 'pizza', 'milk']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like strings, lists are a type of object, and so they also have some methods associated with them, which you can use.  However, unlike strings, these methods mostly change the list in place, rather than returning a new list.  So, when you type"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
933
   "execution_count": null,
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "shopping.sort()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python doesn’t return a value, but if you look at the list, you will see that the order of the items has changed."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
951
   "execution_count": null,
952 953 954
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
955
   "outputs": [],
956 957 958 959 960 961 962 963 964 965 966 967 968
   "source": [
    "shopping"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This means that unlike strings, lists are _mutable_, and individual items and sets of items can be changed in place.  If you decide you want to add items to the list, you can do it with the `.append()` method:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
969
   "execution_count": null,
970 971 972
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
973
   "outputs": [],
974 975 976 977 978 979 980 981 982 983 984 985 986 987
   "source": [
    "shopping.append('mayonnaise')\n",
    "shopping"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you feel it’s important enough to go at the top of the list, you can use `.insert()` to insert the new item at a particular point and shuffle everything else up:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
988
   "execution_count": null,
989 990 991
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
992
   "outputs": [],
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
   "source": [
    "shopping.insert(0, 'mayonnaise')\n",
    "shopping"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Removing items from the list is just as easy - you use `.pop()` to do that.  If you don’t give it an index, it will remove the last item in the list, otherwise `pop` removes the item with the index you specify and shuffles everything else up one position to close the gap. Give it a try, to remove one of the \"mayonnaise\" items in the shopping list. "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1007
   "execution_count": null,
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Sequences"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The two object types that we have talked about so far share a number of properties.  Both strings and lists consist of ordered pieces of data.  In the case of strings this is simple characters.  In lists, the elements of the list can be of any object type."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For both lists and strings we might want to refer to a particular item or range of items in a string or list and we can do this easily:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1039
   "execution_count": null,
1040 1041 1042
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
1043
   "outputs": [],
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
   "source": [
    "words = s.split()\n",
    "print(words[3]) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You will see that \"fox\" is actually the fourth word and this is just one of the things that computers do that you have to get used to.  The first element in a sequence has an index of 0, so"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1058
   "execution_count": null,
1059 1060 1061
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
1062
   "outputs": [],
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
   "source": [
    "print(words[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "gives you the first item in the list. This is referred to as zero-based indexing or offset numbering.  Its origins are in programming languages where variables actually refer to the memory location of the start of the list, and now has just become a tradition.  Negative indices are assumed to be relative to the end of the array, so"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1076
   "execution_count": null,
1077 1078 1079
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
1080
   "outputs": [],
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
   "source": [
    "words[-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "yields the final element in the list, in this case \"dog\".  Of course, if we knew how long the sequence was, we could just use the number of the last element.  For any sequence data type, `len()` will tell us how many elements it has:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1094
   "execution_count": null,
1095 1096 1097
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
1098
   "outputs": [],
1099 1100 1101 1102 1103 1104
   "source": [
    "len(words)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1105
   "execution_count": null,
1106 1107 1108
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
1109
   "outputs": [],
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
   "source": [
    "len(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, since the sequences are indexed from zero, the last element, i.e. `words[-1]`, is the same as `words[len(words)-1]`. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### _Exercise 1.3_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1132
    "There are a few quirks to sequence indexing (apart from starting at 0), and I have tried to summarise these on the Python Cheat Sheet.  Have a go with a few of the \"Indices and Slices\" and make sure you understand how they work.  Then, instead of trying them on a list, try them on a string.  Now, if you are really adventurous, try to print the third letter of the fourth word in the `words` list."
1133 1134 1135 1136
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
1137
   "execution_count": null,
1138 1139 1140 1141 1142 1143 1144 1145
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# type your command(s) here or use the IPython shell..."
   ]
  },
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### _Exercise 1.4_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Below is a set of commands working with a list of cities. First, the list is extended by adding 'Athens' onto the end, and then 'Nairobi' - the third element in the list - is assigned to the variable `kenya`. Some of the code has been removed (replaced with `---`). Fill in the blanks in the code block to make it work."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cities = ['Winnipeg', 'Guangzhou', 'Nairobi', 'Santiago', 'Glasgow']\n",
    "cities.---('Athens') # add 'Athens' onto the end of the list\n",
    "kenya = cities[---] # access the third entry in the cities list"
   ]
  },
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Summary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Python can be used to calculate the results of a wide range of expressions, and print out the results.\n",
    "* Like in all programming languages, variables can be used to store the results of calculations or simple values that we might need to use later.\n",
    "* Variables refer to values.  The values can be numbers (integer and floating point), strings or lists.  You will discover soon that there are other data types as well.\n",
    "* Some data types are objects, which have methods associated with them.  These methods perform common tasks on the values of the objects.\n",
    "* Some data types are sequences, which let us access individual elements at will.\n",
    "* Sequence data types allow us to step through the values in them, but to do that we need to take some first steps towards writing real programs."
   ]
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### _Debugging Exercise_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The lines below have mistakes in them, which produce errors when they are run. Try to identify the problems in the code, and fix them so that they run without error."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cake flavours = ['chocolate', 'coffee', 'carrot', 'vanilla']\n",
    "cake_flavours.append('lemon')\n",
    "  print(cake_flavours)"
   ]
1218 1219 1220
  }
 ],
 "metadata": {
1221
  "celltoolbar": "Edit Metadata",
1222
  "kernelspec": {
1223
   "display_name": "Python 3",
1224
   "language": "python",
1225
   "name": "python3"
1226 1227 1228 1229
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
1230
    "version": 3
1231 1232 1233 1234 1235
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
1236
   "pygments_lexer": "ipython3",
1237
   "version": "3.6.2"
1238 1239 1240 1241 1242
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}