Python Tutorial - Basics.ipynb 41 KB
Newer Older
christian.foerster's avatar
christian.foerster committed
1 2 3 4 5 6 7 8
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A short Introdcution to Python\n",
    "\n",
christian.foerster's avatar
update  
christian.foerster committed
9 10 11 12 13 14 15 16 17 18 19 20
    "## Things you might be wondering:\n",
    "- What is an Anaconda and what does it have to do with Python\n",
    "    - Anaconda program to manage virtual environments\n",
    "    - can be set up in a virtual environment\n",
    "    \n",
    "    \n",
    "- Python 2 vs Python 3?\n",
    "    - unsupported vs. supported\n",
    "    \n",
    "    \n",
    "- Where does Python fit in? \n",
    "     - for educational purposes (https://www.researchgate.net/publication/328175547_MatLab_vs_Python_vs_R)\n",
21
    "     - more generally speaking (https://pyzo.org/python_vs_matlab.html) (R is mainly for data wrangling)\n",
christian.foerster's avatar
update  
christian.foerster committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35
    "     - development -> if you want to develop open source software, that many people can use, you need a open source language!\n",
    "     \n",
    "     \n",
    "- Is Python fast?\n",
    "    - not really\n",
    "    - it can comparable to c++/c/fortran (numpy, cython, numba)\n",
    "    \n",
    "    \n",
    "- Why is Python so popular?\n",
    "    - easy to learn/use\n",
    "    - code readabiltiy \n",
    "    - open source \n",
    "    - huge commuinuty\n",
    "    - general purpose language\n",
christian.foerster's avatar
christian.foerster committed
36 37 38 39 40
    "\n",
    "## Some nice-to-know's\n",
    "* indexing starts at 0\n",
    "* the syntax i controlled mainly by tabs (4 spaces), that mean less brackets and better readability\n",
    " * so you should adapt your texteditor (e.g.: notepad++) to replace a tab with 4 spaces\n",
christian.foerster's avatar
update  
christian.foerster committed
41
    "* commet with hashtag, multiline comments/docstrings like so \"\"\"my comment or docstring\"\"\"\n"
christian.foerster's avatar
christian.foerster committed
42 43 44 45 46 47 48 49 50 51 52
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables and Conversions"
   ]
  },
  {
   "cell_type": "code",
53 54 55
   "execution_count": null,
   "metadata": {},
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
   "source": [
    "# Integer\n",
    "a=25\n",
    "\n",
    "# Float\n",
    "b=5.6\n",
    "\n",
    "# String\n",
    "c=\"6.7\"\n",
    "\n",
    "#Boolean\n",
    "d=True\n",
    "\n",
    "# Variable conversion work as follows. (int() always rounds down)\n",
    "print(float(a),float(c),int(b),str(b),sep=\"\\n\")\n",
    "print(\"Some string\")\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Mind the difference between \\/ and \\/\\/**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**String formatting**\n",
    "\n",
    "For quick and simple formatting"
   ]
  },
  {
   "cell_type": "code",
93
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
94
   "metadata": {},
95
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
   "source": [
    "# Float and int formatting in strings\n",
    "print(\"Ich bin %.2f alt.\" %29.324232) # % für hier muss noch was rein, .2 für 2 Kommastellen, f für float\n",
    "print(\"Ich bin %i alt.\"%29) # ...\n",
    "\n",
    "# concat strings\n",
    "print(\"Ich bin \"+str(29)+\" alt.\")\n",
    "\n",
    "# copy pasting folder paths (use the r\"\" -> raw string mode) \n",
    "print(r\"C:\\adg\\ggj\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For complexer formatting"
   ]
  },
  {
   "cell_type": "code",
117
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
118
   "metadata": {},
119
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133
   "source": [
    "# straight forward without index the format arguments\n",
    "print('{}, {}, {}'.format('a', 'b', 'c'))\n",
    "\n",
    "# indexing the format arguments\n",
    "print('first-{0},second-{1},third-{2}'.format('a', 'b', 'c'))\n",
    "print('{2}, {1}, {0}'.format('a', 'b', 'c',\"d\"))\n",
    "print('{2}, {1}, {0}'.format(*'abcd')) # * unpacks the string into a tuple\n",
    "print('{0}+++{1}---{0}'.format('first', 'second'))\n",
    "\n",
    "# using keyword arguments and indexing in one step\n",
    "print(\"{x}-{x}={z[0]}\".format(x=4,z=[0,7]))"
   ]
  },
134 135 136 137 138 139 140 141 142 143 144 145 146
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# interesting string methods\n",
    "print(\"dd\".replace(\"d\",\"e\"))\n",
    "print(\"edf.ggg\".split(\".\"))\n",
    "print(\"55\".isdigit())\n",
    "# ...\n"
   ]
  },
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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nalso \\none\\n'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# multiline string\n",
    "\"\"\"\n",
    "this is one\n",
    "...\n",
    "\"\"\"\n",
    "# and this\n",
    "'''\n",
    "also \n",
    "one\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# keep in mind\n",
    "''==\"\""
   ]
  },
197 198 199 200 201 202 203
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Math Hints"
   ]
  },
204 205 206 207 208 209 210 211 212 213 214
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Attention!\n",
    "print(\"That's a: \", type(6/3))\n",
    "print(\"And that's a \",type(6//3))"
   ]
  },
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "8^5 # what the hell (https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(0^0,1^1,1^0,0^1, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "8**5 # to the power of"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "-7 // 2 # integer division rounding down!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "13 % 4 # modulo (divison remainder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 3\n",
    "x += 3  # same as x = x + 3\n",
    "x *= 2  # same as x = x * 2\n",
    "x /= 4  # same as x = x / 4\n",
    "x"
   ]
  },
christian.foerster's avatar
christian.foerster committed
273 274 275 276 277 278 279 280 281
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Data Structures \n",
    "\n",
    "- list() -> ordered, mutable structure (indexing via number)\n",
    "- dict() -> unordered structure (indexing via keyword)\n",
    "- tuple() -> ordered, immutable structure (indexing via number)\n",
282
    "- sets() -> unordered,immutable representation with unique values only (does not support indexing)\n",
christian.foerster's avatar
christian.foerster committed
283 284 285 286 287
    "### Lists"
   ]
  },
  {
   "cell_type": "code",
288
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
289
   "metadata": {},
290
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
   "source": [
    "# initiate an empty list\n",
    "mylist=[] # or list()\n",
    "print(mylist)\n",
    "\n",
    "# adding values to a list one at a time\n",
    "mylist.append(2)\n",
    "mylist.append(4)\n",
    "print(mylist)\n",
    "\n",
    "# joining lists, adding mutiple values at once \n",
    "mylist.extend([22,14]) \n",
    "mylist=mylist+[25,43]\n",
    "mylist+=[235,143]\n",
    "print(mylist)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indexing, slicing, reversing lists"
   ]
  },
  {
   "cell_type": "code",
317
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
318
   "metadata": {},
319
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
   "source": [
    "Numbers=[1,2,3,4,5,6,7,8,9,10]\n",
    "# slice\n",
    "print(Numbers[2:5])\n",
    "print(Numbers[:5])\n",
    "\n",
    "# index\n",
    "print(Numbers[0]) # gibt den letzten Wert aus\n",
    "\n",
    "# reverse\n",
    "print(Numbers[::-1])"
   ]
  },
  {
   "cell_type": "code",
335
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
336
   "metadata": {},
337
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
   "source": [
    "# sort\n",
    "Numbers.sort()\n",
    "print(Numbers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What can we store in a list?"
   ]
  },
  {
   "cell_type": "code",
353
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
354
   "metadata": {},
355
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
356 357 358 359 360 361 362 363 364 365
   "source": [
    "# lists, dictionary and tuple are very versatile and can store all possible data structures and other things\n",
    "newlist=[2,3.2,[3],True]\n",
    "\n",
    "# print the type of the stored values\n",
    "print(type(newlist[0]),type(newlist[1]),type(newlist[2]),sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
366 367 368
   "execution_count": null,
   "metadata": {},
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
369 370 371 372 373
   "source": [
    "# string to list \n",
    "list(\"abcdefghijklmnopqrstuvwxyz\")"
   ]
  },
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Attention: pointer or new list?!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a=[4,5,6]\n",
    "b=a\n",
    "b[0]=99\n",
    "b.append(5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "id(a)==id(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "c=a.copy()# copy list (also a[:])\n",
    "c[2]=9999"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "id(a)==id(c)"
   ]
  },
christian.foerster's avatar
christian.foerster committed
439 440 441 442 443 444 445 446 447
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tupel"
   ]
  },
  {
   "cell_type": "code",
448
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
449
   "metadata": {},
450
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
451 452 453 454 455 456 457 458
   "source": [
    "# tuple are intitated with tuple() or ()\n",
    "x = (1, 2, 3)\n",
    "len(x)"
   ]
  },
  {
   "cell_type": "code",
459
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
460
   "metadata": {},
461
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
462 463 464 465 466 467 468 469 470 471
   "source": [
    "# indexing, slicing and reversing is the same as in lists\n",
    "y = (4, 5, 6)\n",
    "print(y[:2])\n",
    "print(y[-1])\n",
    "y[::-1]"
   ]
  },
  {
   "cell_type": "code",
472
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
473
   "metadata": {},
474
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
475 476 477 478 479 480 481 482 483 484 485 486 487 488
   "source": [
    "listOfTuples = [x, y]\n",
    "listOfTuples"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Unpacking of lists and tuples**"
   ]
  },
  {
   "cell_type": "code",
489
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
490
   "metadata": {},
491
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
   "source": [
    "(age, income) = \"32,120000\".split(',')\n",
    "print(age)\n",
    "print(income)\n",
    "print(income.replace(\"0\",\"9\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dictionaries"
   ]
  },
  {
   "cell_type": "code",
508
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
509
   "metadata": {},
510
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
   "source": [
    "# initiate a dictionary {} or dict()\n",
    "lastnames = {}\n",
    "\n",
    "# fill the dictionary\n",
    "lastnames[\"Jakob\"] = \"Benisch\"\n",
    "lastnames[\"Stefanie\"] = \"Wiek\"\n",
    "lastnames[\"Winnie\"] = \"Puh\"\n",
    "lastnames[\"Christian\"] = \"Koch\"\n",
    "lastnames[\"blaa\"]=[1,2,3,43,12,21,3,43]\n",
    "\n",
    "print(lastnames)\n",
    "\n",
    "# indexing\n",
    "print(lastnames[\"Christian\"])"
   ]
  },
  {
   "cell_type": "code",
530
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
531
   "metadata": {},
532
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
533 534 535 536 537 538 539
   "source": [
    "# indexing with error catch\n",
    "print(lastnames.get(\"Bruno\"))\n"
   ]
  },
  {
   "cell_type": "code",
540
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
541
   "metadata": {},
542
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
543 544 545 546 547 548 549
   "source": [
    "# accessing data of a dict\n",
    "print(lastnames.items())\n",
    "print(lastnames.keys())\n",
    "print(lastnames.values())"
   ]
  },
550 551 552 553 554 555 556 557 558 559 560 561 562
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Some problematic as in lists pointers and new dictionary\n",
    "a={\"a\":3}\n",
    "b=a.copy()\n",
    "b[\"a\"]=99\n",
    "a"
   ]
  },
christian.foerster's avatar
christian.foerster committed
563 564 565 566 567 568 569 570 571
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sets"
   ]
  },
  {
   "cell_type": "code",
572
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
573 574 575
   "metadata": {
    "scrolled": false
   },
576
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
577 578 579 580 581 582
   "source": [
    "a={1,2,3,4,3,4,5}\n",
    "print(\"a: {}\".format(a))\n",
    "b=set([2,4,2,2,6,4,23])\n",
    "print(\"b: {}\".format(b))\n",
    "\n",
583
    "print(\"In a but not in b: {}\".format(a.difference(b)))\n"
christian.foerster's avatar
christian.foerster committed
584 585 586 587 588 589 590 591 592 593 594
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**A quick Comparison**"
   ]
  },
  {
   "cell_type": "code",
595
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
596
   "metadata": {},
597
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
598
   "source": [
599
    "# list\n",
christian.foerster's avatar
christian.foerster committed
600
    "[1,2,3,4,5,3]\n",
601
    "# tuple\n",
christian.foerster's avatar
christian.foerster committed
602
    "(3,2,4)\n",
603
    "# dict\n",
christian.foerster's avatar
christian.foerster committed
604
    "{\"myname\":40}\n",
605
    "# set\n",
christian.foerster's avatar
christian.foerster committed
606 607 608
    "{1,2,3}"
   ]
  },
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# For all of these we can use the in statement to check whether a number is in a given list.\n",
    "3 in [3,4] \n",
    "3 in {3:\"for dictionaries the key will be checked\"} \n",
    "3 in (3,4) \n",
    "3 in {3,4}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning by doing!\n",
    "\n",
    "In order to not fall asleep when looking at python syntax, let's have a little break and do some exercises.\n",
    "\n",
    "### Exercise Round 1\n",
    "\n",
    "- What's the remainder of $2^{99}$ divided by $57$?  \n",
    "- If you were to write a little database, that gets one file for every day containing data for that day.  \n",
    "And you want to store the file locations in a basic python data structure. Which one would you use and why?  \n",
    "- If you want to check two large python lists for commen values, how would you do it?"
   ]
  },
christian.foerster's avatar
christian.foerster committed
638 639 640 641 642 643 644 645 646 647
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loops\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
648
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
649 650 651
   "metadata": {
    "scrolled": true
   },
652
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
653 654 655 656 657 658 659 660 661 662 663 664 665
   "source": [
    "# summing up the values of a list\n",
    "summe=0\n",
    "for num in [1,2,3,4]:\n",
    "    # everything that is endeted is within the loop\n",
    "    summe+=num\n",
    "    print(num)\n",
    "    \n",
    "print(\"Summe: \"+str(summe))"
   ]
  },
  {
   "cell_type": "code",
666
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
667
   "metadata": {},
668
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
669 670 671 672 673 674 675
   "source": [
    "for number in [1,2,3,4,[],\"ffffdd\"]:\n",
    "    print(number)"
   ]
  },
  {
   "cell_type": "code",
676
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
677
   "metadata": {},
678
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
679 680 681 682 683 684 685 686 687 688 689
   "source": [
    "# while loop example\n",
    "start=1\n",
    "end=6\n",
    "while start<end:\n",
    "    print(start)\n",
    "    start+=1"
   ]
  },
  {
   "cell_type": "code",
690
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
691 692 693 694 695 696 697 698 699 700 701
   "metadata": {},
   "outputs": [],
   "source": [
    "# be careful with while loop\n",
    "# this one would run endlessly\n",
    "#while True:\n",
    "#    a=1"
   ]
  },
  {
   "cell_type": "code",
702
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
703
   "metadata": {},
704
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
   "source": [
    "# nested loop matrix (m,n) filled with ones, technically speaking its a list not a matrix...\n",
    "m=4\n",
    "n=10\n",
    "\n",
    "matrix=[]\n",
    "for i_m in range(m):\n",
    "    matrix.append([])\n",
    "    for i_n in range(n):\n",
    "        matrix[i_m].append(\"{},{}\".format(i_m,i_n))\n",
    "\n",
    "matrix"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Control Statements\n"
   ]
  },
  {
   "cell_type": "code",
728
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
729
   "metadata": {},
730
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
731 732 733 734 735 736 737 738 739 740 741 742 743
   "source": [
    "a=2\n",
    "if a==3:\n",
    "    print(\"a is 3!\")\n",
    "elif a==1:\n",
    "    print(\"a is 1!\")\n",
    "else:\n",
    "    print(\"a is not 3, nor 1!\")\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
744
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
745
   "metadata": {},
746
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
747 748 749 750 751 752 753 754 755 756 757 758
   "source": [
    "# try rerunning that script \n",
    "if type(age)==str:\n",
    "    print(\"Told you its a string!\")\n",
    "    # converts to an integer\n",
    "    age=int(age)\n",
    "else:\n",
    "    print(\"Guess I was wrong. It's a %s\" %str(type(age)))\n",
    "    #converts to a string\n",
    "    age=str(age)"
   ]
  },
759 760 761 762 763 764 765
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nifty One-Liners"
   ]
  },
christian.foerster's avatar
christian.foerster committed
766 767
  {
   "cell_type": "code",
768
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
769
   "metadata": {},
770
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
771 772 773 774 775 776 777
   "source": [
    "# control statement one - liner\n",
    "3 if 3==3 else \"bollox\""
   ]
  },
  {
   "cell_type": "code",
778 779 780
   "execution_count": null,
   "metadata": {},
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
781 782 783 784 785
   "source": [
    "# fancy list comprehension -> even or uneven?\n",
    "[(True,i) if i%2==0 else (False,i) for i in range(29)]"
   ]
  },
786 787 788 789 790 791 792 793 794 795
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# dictionary comprehension\n",
    "{key: value for key, value in zip([\"a\",\"b\",\"c\"],[1,2,3])}"
   ]
  },
christian.foerster's avatar
update  
christian.foerster committed
796 797 798 799
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
800
    "### Exercise Round 2\n",
christian.foerster's avatar
update  
christian.foerster committed
801 802 803 804
    "\n",
    "Lets write a little program which can be used to analyse files and can count the occurance of patterns in each line!\n",
    "\n",
    "__Pattern Analyser__\n",
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 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 896 897 898 899 900 901 902 903 904 905 906 907
    "\n",
    "Input:  \n",
    "- A string! (later a file)  \n",
    "\n",
    "Output:  \n",
    "- Number of occurances in each line!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Standard Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "help(abs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "min([1,2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "max([1,2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sorted([8,1,2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "len([1,2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "range(99)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "zip([2,3,4],[55,77,66])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "enumerate([3,4,5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sum([3,4,67])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "all([True,True]) and not any([False, False])"
christian.foerster's avatar
update  
christian.foerster committed
908 909
   ]
  },
christian.foerster's avatar
christian.foerster committed
910 911 912 913
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
914
    "## Writing your own Functions"
christian.foerster's avatar
christian.foerster committed
915 916 917 918
   ]
  },
  {
   "cell_type": "code",
919
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
920
   "metadata": {},
921
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
   "source": [
    "# function to add two arguments \n",
    "def sum_1(a,b):\n",
    "    return a+b\n",
    "\n",
    "# funtion with provided default values for arguments\n",
    "def sum_2(a,b=6,c=9,d=98):\n",
    "    '''\n",
    "    this is my docstring\n",
    "    '''\n",
    "    c=a+b+c\n",
    "    return c\n",
    "\n",
    "# this function does add the two input arguments but does not return them\n",
    "def sum_3(a,b):\n",
    "    c=a+b\n",
    "    return 3,4,5\n",
    "\n",
    "# playing around with the defined functions\n",
    "print(sum_1(2,3))\n",
    "print(sum_2(2,c=-44))\n",
    "print(sum_3(2,3))\n"
   ]
  },
  {
   "cell_type": "code",
948
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
949
   "metadata": {},
950
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
951 952 953 954 955 956 957 958 959 960 961 962 963
   "source": [
    "# you can even pass functions as function arguments\n",
    "def add_ten(func,a,b):\n",
    "    '''\n",
    "    my function\n",
    "    '''\n",
    "    return func(a,b)+10\n",
    "\n",
    "print(add_ten(sum_2,0,1))"
   ]
  },
  {
   "cell_type": "code",
964
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
965
   "metadata": {},
966
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
967 968
   "source": [
    "import sys\n",
christian.foerster's avatar
update  
christian.foerster committed
969 970
    "sys.getrecursionlimit()\n",
    "#sys.setrecursionlimit()"
christian.foerster's avatar
christian.foerster committed
971 972 973 974
   ]
  },
  {
   "cell_type": "code",
975
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
976
   "metadata": {},
977
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
   "source": [
    "# recursion works like this (std limit 3000)\n",
    "def factorial_slow(n):\n",
    "    \n",
    "    if n==1:\n",
    "        return n\n",
    "    else:\n",
    "        return n*factorial(n-1)\n",
    "\n",
    "# lets compare the execution time of recursion to a while loop\n",
    "def factorial_fast(m):\n",
    "    \n",
    "    res=1\n",
    "    while m>1:\n",
    "        res*=m\n",
    "        m-=1\n",
    "        \n",
    "    return res\n",
    "\n",
    "def factorial_fastest(number):\n",
    "    \n",
    "    if number == 1 or number == 0:\n",
    "        return 1\n",
    "    \n",
    "    result = 1 # variable to hold the result\n",
    "    for x in range(1, number + 1, 1):\n",
    "        result *= x\n",
    "        \n",
    "    return result\n",
    "\n",
    "# performance check\n",
    "%timeit factorial_slow(2000)\n",
    "%timeit factorial_fast(2000)\n",
    "%timeit factorial_fastest(2000)\n",
    "\n",
christian.foerster's avatar
update  
christian.foerster committed
1013
    "# for is faster than while\n"
christian.foerster's avatar
christian.foerster committed
1014 1015 1016 1017
   ]
  },
  {
   "cell_type": "code",
1018
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1019
   "metadata": {},
1020
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
   "source": [
    "# decorators\n",
    "def pretty_print(func):\n",
    "    def wrap(arg):\n",
    "        symbols=\"-\"*len(arg)\n",
    "        print(symbols)\n",
    "        res=func(arg)\n",
    "        print(symbols)\n",
    "        return res\n",
    "    return wrap\n",
    "\n",
    "@pretty_print\n",
    "def printer(string=3):\n",
    "    print(string)\n",
    "    \n",
    "printer(\" o -|- ofdsgafdgfdsagdsgsa \")"
   ]
  },
  {
   "cell_type": "code",
1041
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1042
   "metadata": {},
1043
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
   "source": [
    "# special function argumentes\n",
    "def arbitiary_number_of_arguments(*args):\n",
    "    print(*args)\n",
    "    print(args)\n",
    "    return \"-\".join([str(a) for a in args])\n",
    "\n",
    "arbitiary_number_of_arguments(2,3,4,5,6)"
   ]
  },
  {
   "cell_type": "code",
1056
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1057
   "metadata": {},
1058
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
   "source": [
    "# special function keyargumentes\n",
    "def arbitiary_number_of_keyword_arguments(**kwargs):\n",
    "    print(kwargs)\n",
    "    \n",
    "arbitiary_number_of_keyword_arguments(ab=2,cd=4,ef=5,gh=\"ee\")"
   ]
  },
  {
   "cell_type": "code",
1069
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1070
   "metadata": {},
1071
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1072 1073 1074 1075 1076 1077 1078 1079
   "source": [
    "# args before kwargs!!\n",
    "def both(*args,**kwargs):\n",
    "    return args,kwargs\n",
    "\n",
    "both(3,4,2,4,5,wa=2,ab=44)"
   ]
  },
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Generators"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# define a generator with the yield statement\n",
    "def squared_range(n):\n",
    "    for i in range(n):\n",
    "        yield i**2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# using a generator in a loop\n",
    "for val in squared_range(8):\n",
    "    print(val)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gen=squared_range(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# use with the next statement\n",
    "next(gen)"
   ]
  },
christian.foerster's avatar
christian.foerster committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Local vs Global Variables\n",
    "\n",
    "Variables can have a local or a global scope. For instance variables used in a function are only known within that function -> local."
   ]
  },
  {
   "cell_type": "code",
1140
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
   "metadata": {},
   "outputs": [],
   "source": [
    "# defining a global variable\n",
    "i_glob=2\n",
    "\n",
    "# a function defined to change the value of i_glob\n",
    "def changeVariable():\n",
    "    i_glob = 33\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
1155
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
   "metadata": {},
   "outputs": [],
   "source": [
    "# which number will be printed????\n",
    "changeVariable()\n",
    "#print(i_glob)"
   ]
  },
  {
   "cell_type": "code",
1166
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1167
   "metadata": {},
1168
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
   "source": [
    "i_glob=2\n",
    "\n",
    "# changing global variables from within a function\n",
    "def changeVariable():\n",
    "    global i_glob\n",
    "    i_glob = 222\n",
    "    return\n",
    "\n",
    "changeVariable()\n",
    "#print(i_glob)\n"
   ]
  },
  {
   "cell_type": "code",
1184
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1185
   "metadata": {},
1186
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
   "source": [
    "# other ways to access local and global variables\n",
    "def test():\n",
    "    a = 9\n",
    "    b = 99\n",
    "    c = 999\n",
    "    print(locals())\n",
    "test()"
   ]
  },
  {
   "cell_type": "code",
1199 1200 1201
   "execution_count": null,
   "metadata": {},
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1202 1203 1204 1205 1206 1207
   "source": [
    "globals()"
   ]
  },
  {
   "cell_type": "code",
1208
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1209
   "metadata": {},
1210
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1211 1212 1213 1214 1215 1216
   "source": [
    "print(a_local)"
   ]
  },
  {
   "cell_type": "code",
1217
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1218
   "metadata": {},
1219
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
   "source": [
    "def update_globals_with_locals():\n",
    "    a_local=\"how convenient\"\n",
    "    globals().update(locals())\n",
    "    return\n",
    "update_globals_with_locals()\n",
    "print(a_local)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import Packages\n",
    "\n",
    "Like in moste programming languages many packages exist... To install packages you can use *pip* (Package Installer Python). If you have anaconda installed you can also use *conda*.\n",
    "\n",
    "Open a terminal/console and install packages like so:\n",
    "**pip install _packagename_** or **conda install _packagename_**\n",
    "\n",
    "Once the desired package is installed you can import it. "
   ]
  },
  {
   "cell_type": "code",
1245
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the package numpy\n",
    "import numpy\n",
    "\n",
    "# import the package numpy to a variable called np\n",
    "import numpy as np\n",
    "\n",
    "# import the function \"array\" from the package numpy\n",
    "from numpy import array\n",
    "\n",
    "# import all functions from the package numpy\n",
    "from numpy import *\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Depending on how you import packages the access to it's functions is slightly different."
   ]
  },
  {
   "cell_type": "code",
1271
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a list\n",
    "Liste=[1,2,3]\n",
    "\n",
    "# import numpy\n",
    "import numpy\n",
    "\n",
    "# convert list to numpy array\n",
    "Array=numpy.array(Liste)"
   ]
  },
  {
   "cell_type": "code",
1287
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
   "metadata": {},
   "outputs": [],
   "source": [
    "# import numpy to variable np\n",
    "import numpy as np\n",
    "\n",
    "# convert list to numpy array\n",
    "Array=np.array(Liste)"
   ]
  },
  {
   "cell_type": "code",
1300
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
   "metadata": {},
   "outputs": [],
   "source": [
    "# import only the array funtion from the package numpy\n",
    "from numpy import array\n",
    "\n",
    "# convert list to numpy array\n",
    "Array=array(Liste)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    "## Working with Files (low level)\n",
    "\n",
    "\n",
    "\n",
    "**opening modes:**  \n",
    "'r' open for reading (default)  \n",
    "'w' open for writing, truncating the file first  \n",
    "'x' open for exclusive creation, failing if the file already exists  \n",
    "'a' open for writing, appending to the end of the file if it exists  \n",
    "'b' binary mode  \n",
    "'t' text mode (default)  \n",
    "'+' open for updating (reading and writing)  "
christian.foerster's avatar
christian.foerster committed
1327 1328 1329 1330
   ]
  },
  {
   "cell_type": "code",
1331
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1332
   "metadata": {},
1333
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1334 1335
   "source": [
    "# read a file line by line\n",
1336
    "myFile=open(\"data/data_file.txt\",\"r\")\n",
christian.foerster's avatar
christian.foerster committed
1337 1338
    "for line in myFile:\n",
    "    print(line)\n",
1339
    "myFile.close()\n"
christian.foerster's avatar
christian.foerster committed
1340 1341 1342 1343
   ]
  },
  {
   "cell_type": "code",
1344
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1345
   "metadata": {},
1346
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1347 1348 1349
   "source": [
    "# keepting the data\n",
    "file_list=[]\n",
1350
    "file=open(\"data/data_file.txt\",\"r\")\n",
christian.foerster's avatar
christian.foerster committed
1351 1352 1353 1354 1355 1356 1357
    "for line in file:\n",
    "    file_list.append(line)\n",
    "file.close()\n"
   ]
  },
  {
   "cell_type": "code",
1358
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1359
   "metadata": {},
1360
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1361 1362
   "source": [
    "# another way (the cleanest, as the file is closed automatically)\n",
1363
    "with open(\"data/data_file.txt\") as f:\n",
christian.foerster's avatar
christian.foerster committed
1364 1365 1366 1367 1368 1369
    "    read_data = f.read()\n",
    "read_data\n"
   ]
  },
  {
   "cell_type": "code",
1370
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1371 1372 1373 1374
   "metadata": {},
   "outputs": [],
   "source": [
    "# writing new file plus creating it (line by line writing)\n",
1375
    "file=open(\"data/data_file_new.txt\",\"w+\")\n",
christian.foerster's avatar
christian.foerster committed
1376 1377 1378 1379 1380
    "for line in file_list:\n",
    "    file.write(line)\n",
    "file.close()\n"
   ]
  },
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise Round 3 \n",
    "\n",
    "Adapt our previous analyser to read a file and analyse it!\n",
    "\n",
    "__Pattern Analyser__  \n",
    "Input: \n",
    " - A file  \n",
    " \n",
    "Output: \n",
    "- A dict containg the line numbers as keys and occurances in that line as value!   \n",
    "  Lines without occurances should not be in the dictionary.\n"
   ]
  },
christian.foerster's avatar
christian.foerster committed
1398 1399 1400 1401 1402 1403 1404
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Object Oriented Programming"
   ]
  },
christian.foerster's avatar
update  
christian.foerster committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Pillars of OOP\n",
    "- Inheritance (a way to reuse your code)\n",
    "- Abstraction (showing only essential features hiding details)\n",
    "- Encapsulation (bind data variables and functions together in a class)\n",
    "- Polymorphism (create functions with same name and different arguments, redefine functions)"
   ]
  },
  {
   "cell_type": "code",
1418
   "execution_count": null,
christian.foerster's avatar
update  
christian.foerster committed
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parent class\n",
    "class Dog:\n",
    "    # Class attribute\n",
    "    species = 'mammal'\n",
    "\n",
    "    # Initializer / Instance attributes\n",
    "    def __init__(self, name, age):\n",
    "        self.name = name\n",
    "        self.age = age\n",
    "\n",
    "    # instance method\n",
    "    def description(self):\n",
    "        return \"{} is {} years old\".format(self.name, self.age)\n",
    "\n",
    "    # instance method\n",
    "    def speak(self, sound):\n",
    "        return \"{} says {}\".format(self.name, sound)\n",
    "\n",
    "    \n",
    "# Child class (inherits from Dog() class)\n",
    "class RussellTerrier(Dog):\n",
    "    def run(self, speed):\n",
    "        return \"{} runs {}\".format(self.name, speed)\n",
    "\n",
    "\n",
    "# Child class (inherits from Dog() class)\n",
    "class Bulldog(Dog):\n",
    "    def run(self, speed):\n",
    "        return \"{} runs {}\".format(self.name, speed)"
   ]
  },
christian.foerster's avatar
christian.foerster committed
1453 1454
  {
   "cell_type": "code",
christian.foerster's avatar
update  
christian.foerster committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Child classes inherit attributes and\n",
    "# behaviors from the parent class\n",
    "jim = Bulldog(\"Jim\", 12)\n",
    "print(jim.description())\n",
    "\n",
    "# Child classes have specific attributes\n",
    "# and behaviors as well\n",
    "print(jim.run(\"slowly\"))\n",
    "\n",
    "# Is jim an instance of Dog()?\n",
    "print(isinstance(jim, Dog))\n",
    "\n",
    "# Is julie an instance of Dog()?\n",
    "julie = Dog(\"Julie\", 100)\n",
    "print(isinstance(julie, Dog))\n",
    "\n",
    "# Is johnny walker an instance of Bulldog()\n",
    "johnnywalker = RussellTerrier(\"Johnny Walker\", 4)\n",
    "print(isinstance(johnnywalker, Bulldog))\n",
    "\n",
    "# Is julie and instance of jim?\n",
    "print(isinstance(julie, RussellTerrier))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Special Methods, hidden Variables, ...\n",
    "Fancy things we can do!"
   ]
  },
  {
   "cell_type": "code",
1493
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
   "metadata": {},
   "outputs": [],
   "source": [
    "class Bank_Account():\n",
    "    bank = \"Some Bank\"\n",
    "    '''my documentation'''\n",
    "    # this function is being run, when the class is initialized. \n",
    "    # (So when an object is created)\n",
    "    def __init__(self, account_balance):\n",
    "        self.balance = account_balance\n",
    "        return\n",
    "    \n",
    "    # this is a method - a function belonging to a class\n",
    "    def withdraw(self, amount):\n",
    "        '''more documentation'''\n",
    "        self.balance -= amount\n",
    "        return\n",
    "    \n",
    "    # this is a method - a function belonging to a class\n",
    "    def deposit(self, amount):\n",
    "        self.balance += amount\n",
    "        return\n",
    "    \n",
    "    # this is a protected method\n",
    "    def _protected(self):\n",
    "        print(\"easy to access...\")\n",
    "    \n",
    "    # this is a hidden method\n",
    "    def __hidden(self):\n",
    "        print(\"can't make python methods more private than this...\")\n",
    "    \n",
    "    # this is a so called magix method, just like __init__\n",
    "    def __add__(self, other):\n",
    "        balanceSum = self.balance + other.balance\n",
    "        print(\"Their future shared account holds {}.\".format(balanceSum))\n",
    "        return self.balance + other.balance\n",
    "    \n",
    "    # the representation of the instance\n",
    "    def __repr__(self):\n",
    "        return \"This is an instance of the class {}.\".format(self.__class__.__name__)"
   ]
  },
  {
   "cell_type": "code",
1538
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1539
   "metadata": {},
1540
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
   "source": [
    "# create objects (objects are instnances of a class)\n",
    "Jana=Bank_Account(33)  \n",
    "Steffen=Bank_Account(644)\n",
    "\n",
    "Jana.withdraw(10)\n",
    "\n",
    "Jana+Steffen"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
1555 1556
    "If you want to know more about OOP check out: https://www.oodesign.com/\n",
    "\n",
christian.foerster's avatar
christian.foerster committed
1557 1558 1559 1560 1561
    "## Error Handling"
   ]
  },
  {
   "cell_type": "code",
1562
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1563
   "metadata": {},
1564
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1565 1566 1567 1568 1569 1570 1571
   "source": [
    "# cause an error\n",
    "\"e\"+3"
   ]
  },
  {
   "cell_type": "code",
1572
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1573
   "metadata": {},
1574
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
   "source": [
    "# catch the error\n",
    "try:\n",
    "    \"e\"+3\n",
    "except:\n",
    "    print(\"Caught it!\")"
   ]
  },
  {
   "cell_type": "code",
1585
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1586
   "metadata": {},
1587
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
   "source": [
    "# better would be to catch a certain error\n",
    "# so that if something unexpected happens you will know what it is\n",
    "try:\n",
    "    \"e\"+3\n",
    "    \n",
    "except :\n",
    "    print(3)\n",
    "    "
   ]
  },
1599 1600 1601 1602 1603 1604 1605
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
christian.foerster's avatar
christian.foerster committed
1606 1607 1608 1609 1610 1611 1612 1613 1614
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Beispiele\n",
    "\n",
    "So jetzt zeigen ich einfach mal ein paar Beispiele und die kannst du ja mal nachvollziehen. Danach bekommst du ein paar Übungsaufgaben."
   ]
  },
christian.foerster's avatar
update  
christian.foerster committed
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Notepad():\n",
    "    def __init__(self):\n",
    "        self.notes = {}\n",
    "        self.selectedNote=None\n",
    "        return\n",
    "    \n",
    "    def _noteNameCheck(self,noteName):\n",
    "        if noteName is None and self.selectedNote is None:\n",
    "            raise ValueError(\"Please provide a noteName.\")\n",
    "        elif noteName is None:\n",
    "            noteName = self.selectedNote\n",
    "        return noteName\n",
    "    \n",
    "    def addNote(self, noteName):\n",
    "        self.selectedNote=noteName\n",
    "        self.notes[noteName] = {}\n",
    "        return self.notes\n",
    "    \n",
    "    def deleteNote(self, noteName=None):\n",
    "        noteName = self._noteNameCheck(noteName)\n",
    "        del self.notes[noteName]\n",
    "        self.selectedNote = None        \n",
    "        return self.notes\n",
    "    \n",
    "    def addEntry(self, entry, noteName=None):\n",
    "        noteName = self._noteNameCheck(noteName)\n",
    "        self.notes[noteName][entry]=\"unmarked\"\n",
    "        return self.notes\n",
    "    \n",
    "    def deleteEntry(self, entry, noteName=None):\n",
    "        noteName = self._noteNameCheck(noteName)\n",
    "        del self.notes[noteName][entry]\n",
    "        return self.notes\n",
    "    \n",
    "    def markEntry(self, entry, noteName=None):\n",
    "        noteName = self._noteNameCheck(noteName)\n",
    "        self.notes[noteName][entry]=\"marked\"\n",
    "        return self.notes\n",
    "    \n",
    "NotepadInstance = Notepad()\n",
    "NotepadInstance.addNote(\"Shopping\")\n",
    "NotepadInstance.addEntry(\"coffee\")\n",
    "NotepadInstance.addEntry(\"milk\")\n",
    "NotepadInstance.addEntry(\"break\")\n",
    "NotepadInstance.addEntry(\"chocolate\")\n",
    "NotepadInstance.markEntry(\"chocolate\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
christian.foerster's avatar
christian.foerster committed
1676 1677
  {
   "cell_type": "code",
1678
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1679
   "metadata": {},
1680
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
   "source": [
    "# create your own error message\n",
    "class WhatHaveYouDoneNowError(Exception):\n",
    "    pass\n",
    "\n",
    "raise WhatHaveYouDoneNowError(\"This error occurs when you do things that fall under the category:'You have done what???????'\")"
   ]
  },
  {
   "cell_type": "code",
1691
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1692
   "metadata": {},
1693
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
   "source": [
    "# list containing numbers from 1 to 10\n",
    "Numbers=list(range(11))[1:]\n",
    "\n",
    "# create a new list containing only even numbers\n",
    "Even=[]\n",
    "for num in Numbers:\n",
    "    if num%2==0:\n",
    "        Even.append(num)\n",
    "print(Even)\n",
    "\n",
    "# the short version with list comprehension\n",
    "# mind the syntax, reads almost like a sentences\n",
    "Even=[num for num in Numbers if num%2==0]\n",
    "print(Even)"
   ]
  },
  {
   "cell_type": "code",
1713 1714 1715
   "execution_count": null,
   "metadata": {},
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
   "source": [
    "# webscraping for a wg easy\n",
    "\n",
    "# popular package for sending HTTP requests\n",
    "import requests\n",
    "# regular expressions\n",
    "import re\n",
    "\n",
    "# get source of webpage\n",
    "r = requests.get(\"https://www.wgzimmer.ch/en/wgzimmer/search/mate/ch/zurich-stadt.html?wc_language=en\")\n",
    "webpage_content = r.text\n",
    "\n",
    "# filtet to find links to flats\n",
    "re.findall('''<a href=\"/en/wgzimmer/search/mate/ch/zurich-stadt/(.+).html\">''',webpage_content)\n"
   ]
  },
  {
   "cell_type": "code",
1734
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1735
   "metadata": {},
1736
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
   "source": [
    "# we'll create function that gets rid of repeating entries in lists\n",
    "Liste=[1]*10+[2,2]+[3]*4\n",
    "print(Liste)\n",
    "\n",
    "def Uniquify_long(L):\n",
    "    unique=[]\n",
    "    for i in L:\n",
    "        if i not in unique:\n",
    "            unique.append(i)\n",
    "    return unique\n",
    "print(\"Result of the long syntax: \"+str(Uniquify_long(Liste)))\n",
    "\n",
    "# or with list comprehension\n",
    "def Uniquify_medium(L):\n",
    "    unique=[]\n",
    "    [unique.append(i) for i in L if i not in unique]\n",
    "    return unique\n",
    "print(\"Result of the medium syntax: \"+str(Uniquify_medium(Liste)))\n",
    "\n",
    "# and the shortest \n",
    "def Uniquify_short(L):\n",
    "    return [num for pos,num in enumerate(L) if num not in L[:pos]]\n",
    "print(\"Result of the short syntax: \"+str(Uniquify_short(Liste)))\n",
    "\n",
    "# thats the most efficient and easiest way\n",
    "print(set(Liste))"
   ]
  },
  {
   "cell_type": "code",
1768
   "execution_count": null,
christian.foerster's avatar
christian.foerster committed
1769 1770 1771
   "metadata": {
    "scrolled": true
   },
1772
   "outputs": [],
christian.foerster's avatar
christian.foerster committed
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
   "source": [
    "# boolean expressions\n",
    "print(1 is not 3)\n",
    "print(True or False)\n",
    "print(True==1)\n",
    "print(False and False == False)\n",
    "print((False and False) == False)"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}