├── 1_list_set_dict.ipynb
├── 2_python_file_handling.ipynb
├── 3_exception_handling.ipynb
├── ObjectOrientedPython.ipynb
└── QnA_Using_llama_GGUF_Model.ipynb
/1_list_set_dict.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "name": "1_list_set_dict.ipynb",
7 | "provenance": [],
8 | "collapsed_sections": []
9 | },
10 | "kernelspec": {
11 | "name": "python3",
12 | "display_name": "Python 3"
13 | }
14 | },
15 | "cells": [
16 | {
17 | "cell_type": "markdown",
18 | "metadata": {
19 | "id": "r4JmHu9hhCHZ",
20 | "colab_type": "text"
21 | },
22 | "source": [
23 | "# LISTS\n",
24 | "\n",
25 | "## A list is a value that contains multiple values in an ordered sequence."
26 | ]
27 | },
28 | {
29 | "cell_type": "markdown",
30 | "metadata": {
31 | "id": "oxh_G1MWi_MY",
32 | "colab_type": "text"
33 | },
34 | "source": [
35 | "## Using indexes to access values in list"
36 | ]
37 | },
38 | {
39 | "cell_type": "code",
40 | "metadata": {
41 | "id": "sOifcJHAi2wY",
42 | "colab_type": "code",
43 | "colab": {}
44 | },
45 | "source": [
46 | "num_list = [0, 1, 2, 2, 3, 5, 6, 13, 21, 34]\n",
47 | "num_list[0]"
48 | ],
49 | "execution_count": 0,
50 | "outputs": []
51 | },
52 | {
53 | "cell_type": "code",
54 | "metadata": {
55 | "id": "880XagOlti80",
56 | "colab_type": "code",
57 | "colab": {}
58 | },
59 | "source": [
60 | "fruits = ['apple', 'cherry', 'banana', 'Lemon', 'Grape']\n",
61 | "fruits[1]"
62 | ],
63 | "execution_count": 0,
64 | "outputs": []
65 | },
66 | {
67 | "cell_type": "code",
68 | "metadata": {
69 | "id": "zKl0a0D7to1I",
70 | "colab_type": "code",
71 | "colab": {}
72 | },
73 | "source": [
74 | "# lists in list\n",
75 | "\n",
76 | "num_list_2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n",
77 | "num_list_2"
78 | ],
79 | "execution_count": 0,
80 | "outputs": []
81 | },
82 | {
83 | "cell_type": "code",
84 | "metadata": {
85 | "id": "i09zmPidt4ao",
86 | "colab_type": "code",
87 | "colab": {}
88 | },
89 | "source": [
90 | "num_list_2[1]"
91 | ],
92 | "execution_count": 0,
93 | "outputs": []
94 | },
95 | {
96 | "cell_type": "code",
97 | "metadata": {
98 | "id": "NYN-0DViuEy7",
99 | "colab_type": "code",
100 | "colab": {}
101 | },
102 | "source": [
103 | "num_list_2[2][0], num_list_2[2][2]"
104 | ],
105 | "execution_count": 0,
106 | "outputs": []
107 | },
108 | {
109 | "cell_type": "markdown",
110 | "metadata": {
111 | "id": "QLNO3ehYkPag",
112 | "colab_type": "text"
113 | },
114 | "source": [
115 | "## Negative Indexes"
116 | ]
117 | },
118 | {
119 | "cell_type": "code",
120 | "metadata": {
121 | "id": "pPDhBlyBkS9E",
122 | "colab_type": "code",
123 | "colab": {}
124 | },
125 | "source": [
126 | "num_list = [0, 1, 2, 2, 3, 5, 6, 13, 21, 34]\n",
127 | "\n",
128 | "num_list[-1]"
129 | ],
130 | "execution_count": 0,
131 | "outputs": []
132 | },
133 | {
134 | "cell_type": "code",
135 | "metadata": {
136 | "id": "dOD7SgcZuXdx",
137 | "colab_type": "code",
138 | "colab": {}
139 | },
140 | "source": [
141 | "num_list[-2]"
142 | ],
143 | "execution_count": 0,
144 | "outputs": []
145 | },
146 | {
147 | "cell_type": "markdown",
148 | "metadata": {
149 | "id": "azasVVDskZZJ",
150 | "colab_type": "text"
151 | },
152 | "source": [
153 | "## Getting Sublists with Slices"
154 | ]
155 | },
156 | {
157 | "cell_type": "code",
158 | "metadata": {
159 | "id": "rUmWZKG-kaMk",
160 | "colab_type": "code",
161 | "colab": {}
162 | },
163 | "source": [
164 | "num_list[0:3]"
165 | ],
166 | "execution_count": 0,
167 | "outputs": []
168 | },
169 | {
170 | "cell_type": "code",
171 | "metadata": {
172 | "id": "DgJpvtrJult0",
173 | "colab_type": "code",
174 | "colab": {}
175 | },
176 | "source": [
177 | "num_list[3:]"
178 | ],
179 | "execution_count": 0,
180 | "outputs": []
181 | },
182 | {
183 | "cell_type": "code",
184 | "metadata": {
185 | "id": "QWJkJH1Huq8j",
186 | "colab_type": "code",
187 | "colab": {}
188 | },
189 | "source": [
190 | "num_list[:]"
191 | ],
192 | "execution_count": 0,
193 | "outputs": []
194 | },
195 | {
196 | "cell_type": "code",
197 | "metadata": {
198 | "id": "krB2R6czuxcg",
199 | "colab_type": "code",
200 | "colab": {}
201 | },
202 | "source": [
203 | "sub_list = num_list[0:7:2]\n",
204 | "sub_list"
205 | ],
206 | "execution_count": 0,
207 | "outputs": []
208 | },
209 | {
210 | "cell_type": "code",
211 | "metadata": {
212 | "id": "DJm0eN6Au9gt",
213 | "colab_type": "code",
214 | "colab": {}
215 | },
216 | "source": [
217 | "num_list"
218 | ],
219 | "execution_count": 0,
220 | "outputs": []
221 | },
222 | {
223 | "cell_type": "code",
224 | "metadata": {
225 | "id": "ehTkb0AVrgz9",
226 | "colab_type": "code",
227 | "colab": {}
228 | },
229 | "source": [
230 | "num_list[::-1]"
231 | ],
232 | "execution_count": 0,
233 | "outputs": []
234 | },
235 | {
236 | "cell_type": "markdown",
237 | "metadata": {
238 | "id": "yVvYa4Q5ka2D",
239 | "colab_type": "text"
240 | },
241 | "source": [
242 | "## Length of list function _len()_"
243 | ]
244 | },
245 | {
246 | "cell_type": "code",
247 | "metadata": {
248 | "id": "qPHcQhWikhO6",
249 | "colab_type": "code",
250 | "colab": {}
251 | },
252 | "source": [
253 | "len(num_list)"
254 | ],
255 | "execution_count": 0,
256 | "outputs": []
257 | },
258 | {
259 | "cell_type": "code",
260 | "metadata": {
261 | "id": "SRo0pRtPwLmj",
262 | "colab_type": "code",
263 | "colab": {}
264 | },
265 | "source": [
266 | "len(fruits)"
267 | ],
268 | "execution_count": 0,
269 | "outputs": []
270 | },
271 | {
272 | "cell_type": "markdown",
273 | "metadata": {
274 | "id": "YzbgMsg9kpS7",
275 | "colab_type": "text"
276 | },
277 | "source": [
278 | "## Update list values with indexes"
279 | ]
280 | },
281 | {
282 | "cell_type": "code",
283 | "metadata": {
284 | "id": "gcaZdoSvkslu",
285 | "colab_type": "code",
286 | "colab": {}
287 | },
288 | "source": [
289 | "fruits = ['apple', 'cherry', 'banana', 'Lemon', 'Grape']\n",
290 | "fruits[2] = 'orange'"
291 | ],
292 | "execution_count": 0,
293 | "outputs": []
294 | },
295 | {
296 | "cell_type": "code",
297 | "metadata": {
298 | "id": "ePgtC7iOvMIt",
299 | "colab_type": "code",
300 | "colab": {}
301 | },
302 | "source": [
303 | "fruits"
304 | ],
305 | "execution_count": 0,
306 | "outputs": []
307 | },
308 | {
309 | "cell_type": "code",
310 | "metadata": {
311 | "id": "_TsogO9FvMLJ",
312 | "colab_type": "code",
313 | "colab": {}
314 | },
315 | "source": [
316 | "sub_list = num_list[0:3]\n",
317 | "sub_list"
318 | ],
319 | "execution_count": 0,
320 | "outputs": []
321 | },
322 | {
323 | "cell_type": "code",
324 | "metadata": {
325 | "id": "ZKN2vhdRvS4R",
326 | "colab_type": "code",
327 | "colab": {}
328 | },
329 | "source": [
330 | "sub_list[1] = 10\n",
331 | "sub_list"
332 | ],
333 | "execution_count": 0,
334 | "outputs": []
335 | },
336 | {
337 | "cell_type": "code",
338 | "metadata": {
339 | "id": "rXiX5dqhvMN5",
340 | "colab_type": "code",
341 | "colab": {}
342 | },
343 | "source": [
344 | "num_list"
345 | ],
346 | "execution_count": 0,
347 | "outputs": []
348 | },
349 | {
350 | "cell_type": "markdown",
351 | "metadata": {
352 | "id": "fz8tDYuxwRmV",
353 | "colab_type": "text"
354 | },
355 | "source": [
356 | "## Append to list"
357 | ]
358 | },
359 | {
360 | "cell_type": "code",
361 | "metadata": {
362 | "id": "b5CNFOysk0T-",
363 | "colab_type": "code",
364 | "colab": {}
365 | },
366 | "source": [
367 | "fruits"
368 | ],
369 | "execution_count": 0,
370 | "outputs": []
371 | },
372 | {
373 | "cell_type": "code",
374 | "metadata": {
375 | "id": "PtRysjrhwW5W",
376 | "colab_type": "code",
377 | "colab": {}
378 | },
379 | "source": [
380 | "fruits.append('banana')\n",
381 | "fruits.append('peach')\n",
382 | "fruits"
383 | ],
384 | "execution_count": 0,
385 | "outputs": []
386 | },
387 | {
388 | "cell_type": "markdown",
389 | "metadata": {
390 | "id": "8Q01fdEMwv7h",
391 | "colab_type": "text"
392 | },
393 | "source": [
394 | "## List Concatenation and List Replication\n"
395 | ]
396 | },
397 | {
398 | "cell_type": "code",
399 | "metadata": {
400 | "id": "DGgCEKt-wxey",
401 | "colab_type": "code",
402 | "colab": {}
403 | },
404 | "source": [
405 | "fruits_nums = fruits + num_list\n",
406 | "fruits_nums"
407 | ],
408 | "execution_count": 0,
409 | "outputs": []
410 | },
411 | {
412 | "cell_type": "code",
413 | "metadata": {
414 | "id": "ZkEeSzaowxjz",
415 | "colab_type": "code",
416 | "colab": {}
417 | },
418 | "source": [
419 | "short_list = ['a', 'b', 'c']\n",
420 | "short_list"
421 | ],
422 | "execution_count": 0,
423 | "outputs": []
424 | },
425 | {
426 | "cell_type": "code",
427 | "metadata": {
428 | "id": "lZixEpJGyQSV",
429 | "colab_type": "code",
430 | "colab": {}
431 | },
432 | "source": [
433 | "short_list * 3"
434 | ],
435 | "execution_count": 0,
436 | "outputs": []
437 | },
438 | {
439 | "cell_type": "markdown",
440 | "metadata": {
441 | "id": "udaSrYlbk67z",
442 | "colab_type": "text"
443 | },
444 | "source": [
445 | "## Insert to list"
446 | ]
447 | },
448 | {
449 | "cell_type": "code",
450 | "metadata": {
451 | "id": "PAkSsLUqyykM",
452 | "colab_type": "code",
453 | "colab": {}
454 | },
455 | "source": [
456 | "fruits.insert(0, 'avocado')\n",
457 | "fruits"
458 | ],
459 | "execution_count": 0,
460 | "outputs": []
461 | },
462 | {
463 | "cell_type": "code",
464 | "metadata": {
465 | "id": "c5CfivTe0v_B",
466 | "colab_type": "code",
467 | "colab": {}
468 | },
469 | "source": [
470 | "fruits.insert(3, 'pear')"
471 | ],
472 | "execution_count": 0,
473 | "outputs": []
474 | },
475 | {
476 | "cell_type": "code",
477 | "metadata": {
478 | "id": "83pC4eRQ084z",
479 | "colab_type": "code",
480 | "colab": {}
481 | },
482 | "source": [
483 | "fruits"
484 | ],
485 | "execution_count": 0,
486 | "outputs": []
487 | },
488 | {
489 | "cell_type": "markdown",
490 | "metadata": {
491 | "id": "-v5iPpC74o0z",
492 | "colab_type": "text"
493 | },
494 | "source": [
495 | "## Removing Values from Lists with _del_ Statements\n",
496 | "_del_ statement removes the value at given index"
497 | ]
498 | },
499 | {
500 | "cell_type": "code",
501 | "metadata": {
502 | "id": "SLGavPPg4yf0",
503 | "colab_type": "code",
504 | "colab": {}
505 | },
506 | "source": [
507 | "fruits"
508 | ],
509 | "execution_count": 0,
510 | "outputs": []
511 | },
512 | {
513 | "cell_type": "code",
514 | "metadata": {
515 | "id": "5CesmZpv4ykU",
516 | "colab_type": "code",
517 | "colab": {}
518 | },
519 | "source": [
520 | "del fruits[3] # remove element at index 3\n",
521 | "fruits"
522 | ],
523 | "execution_count": 0,
524 | "outputs": []
525 | },
526 | {
527 | "cell_type": "markdown",
528 | "metadata": {
529 | "id": "XRXCiTf15F_Y",
530 | "colab_type": "text"
531 | },
532 | "source": [
533 | "## Removing Values from Lists with _remove_ function\n",
534 | "Function _remove()_ removes the first matching value from the list"
535 | ]
536 | },
537 | {
538 | "cell_type": "code",
539 | "metadata": {
540 | "id": "79Fd2Ho_5L-m",
541 | "colab_type": "code",
542 | "colab": {}
543 | },
544 | "source": [
545 | "numbers = [3, 2, 5, 7, 9, 3, 5]\n",
546 | "numbers"
547 | ],
548 | "execution_count": 0,
549 | "outputs": []
550 | },
551 | {
552 | "cell_type": "code",
553 | "metadata": {
554 | "id": "eHX7e5zH5XjB",
555 | "colab_type": "code",
556 | "colab": {}
557 | },
558 | "source": [
559 | "numbers.remove(5) # remove first element with value = 5\n",
560 | "numbers"
561 | ],
562 | "execution_count": 0,
563 | "outputs": []
564 | },
565 | {
566 | "cell_type": "code",
567 | "metadata": {
568 | "id": "oc8bFQAB5pna",
569 | "colab_type": "code",
570 | "colab": {}
571 | },
572 | "source": [
573 | "fruits.append('cherry')\n",
574 | "fruits.append('orange')\n",
575 | "fruits"
576 | ],
577 | "execution_count": 0,
578 | "outputs": []
579 | },
580 | {
581 | "cell_type": "code",
582 | "metadata": {
583 | "id": "KE33UJ6f5rti",
584 | "colab_type": "code",
585 | "colab": {}
586 | },
587 | "source": [
588 | "fruits.remove('cherry')\n",
589 | "fruits"
590 | ],
591 | "execution_count": 0,
592 | "outputs": []
593 | },
594 | {
595 | "cell_type": "markdown",
596 | "metadata": {
597 | "id": "u6SLBZgp57X3",
598 | "colab_type": "text"
599 | },
600 | "source": [
601 | "## Removing values from Lists with _pop_ function\n",
602 | "function _pop()_ removes value at given index and returns it\n",
603 | "\n",
604 | "if no index is given, last value will be removed and returned"
605 | ]
606 | },
607 | {
608 | "cell_type": "code",
609 | "metadata": {
610 | "id": "a2Gj0pXp6DrM",
611 | "colab_type": "code",
612 | "colab": {}
613 | },
614 | "source": [
615 | "print('fruits: ', fruits)\n",
616 | "a = fruits.pop() # last value if no index is given\n",
617 | "print('a: ', a)\n",
618 | "print('fruits: ', fruits)"
619 | ],
620 | "execution_count": 0,
621 | "outputs": []
622 | },
623 | {
624 | "cell_type": "code",
625 | "metadata": {
626 | "id": "UUAgPS-c6ECl",
627 | "colab_type": "code",
628 | "colab": {}
629 | },
630 | "source": [
631 | "b = fruits.pop()\n",
632 | "print('b: ', b)\n",
633 | "print('fruits: ', fruits)"
634 | ],
635 | "execution_count": 0,
636 | "outputs": []
637 | },
638 | {
639 | "cell_type": "code",
640 | "metadata": {
641 | "id": "2TA1bn8W6gOs",
642 | "colab_type": "code",
643 | "colab": {}
644 | },
645 | "source": [
646 | "print(numbers)\n",
647 | "n = numbers.pop(3)\n",
648 | "print('popped value at index 3: ', n)\n",
649 | "print(numbers)"
650 | ],
651 | "execution_count": 0,
652 | "outputs": []
653 | },
654 | {
655 | "cell_type": "markdown",
656 | "metadata": {
657 | "id": "kO45fRoh5iFW",
658 | "colab_type": "text"
659 | },
660 | "source": [
661 | "## For loop with list\n"
662 | ]
663 | },
664 | {
665 | "cell_type": "code",
666 | "metadata": {
667 | "id": "P7Rovo_25n-C",
668 | "colab_type": "code",
669 | "colab": {}
670 | },
671 | "source": [
672 | "num_list = [0, 1, 2, 2, 3, 5, 6, 13, 21, 34]\n",
673 | "\n",
674 | "# sum of the numbers in the list\n",
675 | "\n",
676 | "sum = 0\n",
677 | "for item in num_list:\n",
678 | " sum += item\n",
679 | " \n",
680 | "print(sum)"
681 | ],
682 | "execution_count": 0,
683 | "outputs": []
684 | },
685 | {
686 | "cell_type": "code",
687 | "metadata": {
688 | "id": "pxcMxPXA50Uf",
689 | "colab_type": "code",
690 | "colab": {}
691 | },
692 | "source": [
693 | "# or use index\n",
694 | "sum = 0\n",
695 | "\n",
696 | "for i in range(len(num_list)):\n",
697 | " sum = sum + num_list[i]\n",
698 | " \n",
699 | "print(sum)"
700 | ],
701 | "execution_count": 0,
702 | "outputs": []
703 | },
704 | {
705 | "cell_type": "code",
706 | "metadata": {
707 | "id": "52RLHprj5_b5",
708 | "colab_type": "code",
709 | "colab": {}
710 | },
711 | "source": [
712 | "## The in and not in Operators\n",
713 | "print(31 in num_list)\n",
714 | "print(13 in num_list)\n",
715 | "print('hello' not in num_list)"
716 | ],
717 | "execution_count": 0,
718 | "outputs": []
719 | },
720 | {
721 | "cell_type": "markdown",
722 | "metadata": {
723 | "id": "mt7ZrmZm6czz",
724 | "colab_type": "text"
725 | },
726 | "source": [
727 | "## Sorting the Values in a List with the sort() Method"
728 | ]
729 | },
730 | {
731 | "cell_type": "code",
732 | "metadata": {
733 | "id": "uJSR-D4O8dWY",
734 | "colab_type": "code",
735 | "colab": {}
736 | },
737 | "source": [
738 | "numbers = [100, -23, 4.56, 290, 33, 7]\n",
739 | "numbers"
740 | ],
741 | "execution_count": 0,
742 | "outputs": []
743 | },
744 | {
745 | "cell_type": "code",
746 | "metadata": {
747 | "id": "1BNX3dBt8l6Z",
748 | "colab_type": "code",
749 | "colab": {}
750 | },
751 | "source": [
752 | "numbers.sort()\n",
753 | "numbers"
754 | ],
755 | "execution_count": 0,
756 | "outputs": []
757 | },
758 | {
759 | "cell_type": "code",
760 | "metadata": {
761 | "id": "aeRk7J3D8vBU",
762 | "colab_type": "code",
763 | "colab": {}
764 | },
765 | "source": [
766 | "numbers.sort(reverse=True)\n",
767 | "numbers"
768 | ],
769 | "execution_count": 0,
770 | "outputs": []
771 | },
772 | {
773 | "cell_type": "code",
774 | "metadata": {
775 | "id": "4j5rBvXv88B0",
776 | "colab_type": "code",
777 | "colab": {}
778 | },
779 | "source": [
780 | "fruits.sort(reverse=True)\n",
781 | "fruits"
782 | ],
783 | "execution_count": 0,
784 | "outputs": []
785 | },
786 | {
787 | "cell_type": "code",
788 | "metadata": {
789 | "id": "NqXZQdVQ82aI",
790 | "colab_type": "code",
791 | "colab": {}
792 | },
793 | "source": [
794 | "# doesn't work\n",
795 | "not_sortable = ['apple', 1, 3.14, 'cat']\n",
796 | "not_sortable.sort()"
797 | ],
798 | "execution_count": 0,
799 | "outputs": []
800 | },
801 | {
802 | "cell_type": "markdown",
803 | "metadata": {
804 | "id": "_Ps20hzX8Ohc",
805 | "colab_type": "text"
806 | },
807 | "source": [
808 | "## List-like type: Tuples\n",
809 | "* tuples support many operations like lists: indexing, slicing, len(), in and not operators, etc. \n",
810 | "* tuples are typed with parentheses (), not square brackets []\n",
811 | "* tuples are IMMUTABLE, while lists are MUTABLE"
812 | ]
813 | },
814 | {
815 | "cell_type": "code",
816 | "metadata": {
817 | "id": "94Ps3gCY-s_1",
818 | "colab_type": "code",
819 | "colab": {}
820 | },
821 | "source": [
822 | "tom = ('Tom', 5, 3.75)\n",
823 | "jerry = ('Jerry', 3, 3.89)\n"
824 | ],
825 | "execution_count": 0,
826 | "outputs": []
827 | },
828 | {
829 | "cell_type": "code",
830 | "metadata": {
831 | "id": "xmoGLdwk-5eh",
832 | "colab_type": "code",
833 | "colab": {}
834 | },
835 | "source": [
836 | "tom[0], tom[1]"
837 | ],
838 | "execution_count": 0,
839 | "outputs": []
840 | },
841 | {
842 | "cell_type": "code",
843 | "metadata": {
844 | "id": "WEq9nqzu--N0",
845 | "colab_type": "code",
846 | "colab": {}
847 | },
848 | "source": [
849 | "tom[1] = 6 # doesn't work, because tuples are IMMUTABLE"
850 | ],
851 | "execution_count": 0,
852 | "outputs": []
853 | },
854 | {
855 | "cell_type": "code",
856 | "metadata": {
857 | "id": "1mRJSbIC_KmY",
858 | "colab_type": "code",
859 | "colab": {}
860 | },
861 | "source": [
862 | "# convert to a list\n",
863 | "tom_list = list(tom)\n",
864 | "tom_list"
865 | ],
866 | "execution_count": 0,
867 | "outputs": []
868 | },
869 | {
870 | "cell_type": "code",
871 | "metadata": {
872 | "id": "05qlR0Fj_QSt",
873 | "colab_type": "code",
874 | "colab": {}
875 | },
876 | "source": [
877 | "# then we can change it, because lists are MUTABLE\n",
878 | "tom_list[1] = 6\n",
879 | "tom_list"
880 | ],
881 | "execution_count": 0,
882 | "outputs": []
883 | },
884 | {
885 | "cell_type": "code",
886 | "metadata": {
887 | "id": "BoT_FW-e_XQM",
888 | "colab_type": "code",
889 | "colab": {}
890 | },
891 | "source": [
892 | "# we can change it back to tuple\n",
893 | "tom = tuple(tom_list)\n",
894 | "tom"
895 | ],
896 | "execution_count": 0,
897 | "outputs": []
898 | },
899 | {
900 | "cell_type": "markdown",
901 | "metadata": {
902 | "id": "VVQ5jbty6c4f",
903 | "colab_type": "text"
904 | },
905 | "source": [
906 | "## Strings are also List-like and IMMUTABLE"
907 | ]
908 | },
909 | {
910 | "cell_type": "code",
911 | "metadata": {
912 | "id": "rzCXjX7k_wby",
913 | "colab_type": "code",
914 | "colab": {}
915 | },
916 | "source": [
917 | "name = 'Tom'\n",
918 | "name[2]"
919 | ],
920 | "execution_count": 0,
921 | "outputs": []
922 | },
923 | {
924 | "cell_type": "code",
925 | "metadata": {
926 | "id": "PZ1NPQMhAJxR",
927 | "colab_type": "code",
928 | "colab": {}
929 | },
930 | "source": [
931 | "len(name)"
932 | ],
933 | "execution_count": 0,
934 | "outputs": []
935 | },
936 | {
937 | "cell_type": "markdown",
938 | "metadata": {
939 | "id": "k_e0zb50oV_L",
940 | "colab_type": "text"
941 | },
942 | "source": [
943 | "## Reference to list"
944 | ]
945 | },
946 | {
947 | "cell_type": "code",
948 | "metadata": {
949 | "id": "QddTa-L6A2ZQ",
950 | "colab_type": "code",
951 | "colab": {}
952 | },
953 | "source": [
954 | "# a number list\n",
955 | "outer_list = [1 ,2, 5.6, 100]\n",
956 | "inner_list = ['a', 'b', 'c']"
957 | ],
958 | "execution_count": 0,
959 | "outputs": []
960 | },
961 | {
962 | "cell_type": "code",
963 | "metadata": {
964 | "id": "NRDchiPZBDXz",
965 | "colab_type": "code",
966 | "colab": {}
967 | },
968 | "source": [
969 | "outer_list[1] = inner_list # index 1 in a_list holds a reference to inner_list\n",
970 | "outer_list"
971 | ],
972 | "execution_count": 0,
973 | "outputs": []
974 | },
975 | {
976 | "cell_type": "code",
977 | "metadata": {
978 | "id": "ayZlOvN7BJeX",
979 | "colab_type": "code",
980 | "colab": {}
981 | },
982 | "source": [
983 | "inner_list.append('d') # update inner_list affects outer_list\n",
984 | "outer_list"
985 | ],
986 | "execution_count": 0,
987 | "outputs": []
988 | },
989 | {
990 | "cell_type": "markdown",
991 | "metadata": {
992 | "id": "7Zzvm_Zq-Kny",
993 | "colab_type": "text"
994 | },
995 | "source": [
996 | "## Lists are passed into functions by reference value"
997 | ]
998 | },
999 | {
1000 | "cell_type": "code",
1001 | "metadata": {
1002 | "id": "uslPzCgmB5uh",
1003 | "colab_type": "code",
1004 | "colab": {}
1005 | },
1006 | "source": [
1007 | "def append_to_list(a_list):\n",
1008 | " a_list.append('extra')\n",
1009 | " \n",
1010 | "my_list = [1, 2, 3]\n",
1011 | "append_to_list(my_list)\n",
1012 | "my_list"
1013 | ],
1014 | "execution_count": 0,
1015 | "outputs": []
1016 | },
1017 | {
1018 | "cell_type": "markdown",
1019 | "metadata": {
1020 | "id": "DTy_NhAIB9Dg",
1021 | "colab_type": "text"
1022 | },
1023 | "source": [
1024 | "##List comprehension"
1025 | ]
1026 | },
1027 | {
1028 | "cell_type": "code",
1029 | "metadata": {
1030 | "id": "RdaTRv_k6fgt",
1031 | "colab_type": "code",
1032 | "colab": {}
1033 | },
1034 | "source": [
1035 | "nums = [1, 2, 3, 4, 5]\n",
1036 | "squares = [ n*n for n in nums ]\n",
1037 | "print(squares)"
1038 | ],
1039 | "execution_count": 0,
1040 | "outputs": []
1041 | },
1042 | {
1043 | "cell_type": "code",
1044 | "metadata": {
1045 | "id": "_xlkjNT4Ec5r",
1046 | "colab_type": "code",
1047 | "colab": {}
1048 | },
1049 | "source": [
1050 | "nums = [4, 5, 3, 6, 7, 2, 1, 9]\n",
1051 | "odds = [ n for n in nums if n % 2 == 1]\n",
1052 | "print(odds)"
1053 | ],
1054 | "execution_count": 0,
1055 | "outputs": []
1056 | },
1057 | {
1058 | "cell_type": "code",
1059 | "metadata": {
1060 | "id": "QxOoFKZlE554",
1061 | "colab_type": "code",
1062 | "colab": {}
1063 | },
1064 | "source": [
1065 | "quotes = \"Imagination is more important than knowledge\"\n",
1066 | "tokens = quotes.split()\n"
1067 | ],
1068 | "execution_count": 0,
1069 | "outputs": []
1070 | },
1071 | {
1072 | "cell_type": "code",
1073 | "metadata": {
1074 | "id": "8p1q9e0gFRt5",
1075 | "colab_type": "code",
1076 | "colab": {}
1077 | },
1078 | "source": [
1079 | "lens = [ len(tk) for tk in quotes.split() ]\n",
1080 | "lens"
1081 | ],
1082 | "execution_count": 0,
1083 | "outputs": []
1084 | },
1085 | {
1086 | "cell_type": "code",
1087 | "metadata": {
1088 | "id": "y4pYHU26FbUn",
1089 | "colab_type": "code",
1090 | "colab": {}
1091 | },
1092 | "source": [
1093 | "token_lens = [ (tk, len(tk)) for tk in quotes.split() ]\n",
1094 | "token_lens"
1095 | ],
1096 | "execution_count": 0,
1097 | "outputs": []
1098 | },
1099 | {
1100 | "cell_type": "markdown",
1101 | "metadata": {
1102 | "id": "vOb-Wp-yGD6M",
1103 | "colab_type": "text"
1104 | },
1105 | "source": [
1106 | "## Need help? dir(list) or help(list)"
1107 | ]
1108 | },
1109 | {
1110 | "cell_type": "code",
1111 | "metadata": {
1112 | "id": "8O5C6MJPGHz6",
1113 | "colab_type": "code",
1114 | "colab": {}
1115 | },
1116 | "source": [
1117 | "dir(list)"
1118 | ],
1119 | "execution_count": 0,
1120 | "outputs": []
1121 | },
1122 | {
1123 | "cell_type": "markdown",
1124 | "metadata": {
1125 | "id": "FiaO01INAb3V",
1126 | "colab_type": "text"
1127 | },
1128 | "source": [
1129 | "# SETS\n",
1130 | "\n",
1131 | "A Set is collection, unordered, iterable, mutable, no duplicate elements. \n",
1132 | "Think of sets in math."
1133 | ]
1134 | },
1135 | {
1136 | "cell_type": "code",
1137 | "metadata": {
1138 | "id": "Pu4GQDgQB1NQ",
1139 | "colab_type": "code",
1140 | "colab": {}
1141 | },
1142 | "source": [
1143 | "set_1 = set()\n",
1144 | "set_2 = {2, 3, 4, 5, 3, 4, 3, 7}"
1145 | ],
1146 | "execution_count": 0,
1147 | "outputs": []
1148 | },
1149 | {
1150 | "cell_type": "code",
1151 | "metadata": {
1152 | "id": "zwYZT2wNCI8_",
1153 | "colab_type": "code",
1154 | "colab": {}
1155 | },
1156 | "source": [
1157 | "type(set_1), set_1"
1158 | ],
1159 | "execution_count": 0,
1160 | "outputs": []
1161 | },
1162 | {
1163 | "cell_type": "code",
1164 | "metadata": {
1165 | "id": "GmqE86w3B670",
1166 | "colab_type": "code",
1167 | "colab": {}
1168 | },
1169 | "source": [
1170 | "type(set_2), set_2"
1171 | ],
1172 | "execution_count": 0,
1173 | "outputs": []
1174 | },
1175 | {
1176 | "cell_type": "markdown",
1177 | "metadata": {
1178 | "id": "KUlCE1XbCYTX",
1179 | "colab_type": "text"
1180 | },
1181 | "source": [
1182 | "## Add to set"
1183 | ]
1184 | },
1185 | {
1186 | "cell_type": "code",
1187 | "metadata": {
1188 | "id": "X_y5_O_rCUTR",
1189 | "colab_type": "code",
1190 | "colab": {}
1191 | },
1192 | "source": [
1193 | "set_1.add(7)\n",
1194 | "set_1.add('dog')\n",
1195 | "set_1.add('dog')\n",
1196 | "set_1.add(3.1415926)\n",
1197 | "set_1"
1198 | ],
1199 | "execution_count": 0,
1200 | "outputs": []
1201 | },
1202 | {
1203 | "cell_type": "markdown",
1204 | "metadata": {
1205 | "id": "ddmjc550Cwji",
1206 | "colab_type": "text"
1207 | },
1208 | "source": [
1209 | "## Union of sets"
1210 | ]
1211 | },
1212 | {
1213 | "cell_type": "code",
1214 | "metadata": {
1215 | "id": "d7LSBbwHDAQ-",
1216 | "colab_type": "code",
1217 | "colab": {}
1218 | },
1219 | "source": [
1220 | "set_1.union(set_2)"
1221 | ],
1222 | "execution_count": 0,
1223 | "outputs": []
1224 | },
1225 | {
1226 | "cell_type": "code",
1227 | "metadata": {
1228 | "id": "osIBYeghDA-k",
1229 | "colab_type": "code",
1230 | "colab": {}
1231 | },
1232 | "source": [
1233 | "set_1 | set_2"
1234 | ],
1235 | "execution_count": 0,
1236 | "outputs": []
1237 | },
1238 | {
1239 | "cell_type": "markdown",
1240 | "metadata": {
1241 | "id": "4iQqeWUVDIE4",
1242 | "colab_type": "text"
1243 | },
1244 | "source": [
1245 | "## Intersect of sets"
1246 | ]
1247 | },
1248 | {
1249 | "cell_type": "code",
1250 | "metadata": {
1251 | "id": "YPl-1-q_DbIP",
1252 | "colab_type": "code",
1253 | "colab": {}
1254 | },
1255 | "source": [
1256 | "set_1.intersection(set_2)"
1257 | ],
1258 | "execution_count": 0,
1259 | "outputs": []
1260 | },
1261 | {
1262 | "cell_type": "code",
1263 | "metadata": {
1264 | "id": "1uI6_k7bDbMH",
1265 | "colab_type": "code",
1266 | "colab": {}
1267 | },
1268 | "source": [
1269 | "set_2 & set_1"
1270 | ],
1271 | "execution_count": 0,
1272 | "outputs": []
1273 | },
1274 | {
1275 | "cell_type": "markdown",
1276 | "metadata": {
1277 | "id": "7pC9F9qEDi1X",
1278 | "colab_type": "text"
1279 | },
1280 | "source": [
1281 | "## Difference of sets"
1282 | ]
1283 | },
1284 | {
1285 | "cell_type": "code",
1286 | "metadata": {
1287 | "id": "qW02WTLyDmvu",
1288 | "colab_type": "code",
1289 | "colab": {}
1290 | },
1291 | "source": [
1292 | "set_2 - set_1"
1293 | ],
1294 | "execution_count": 0,
1295 | "outputs": []
1296 | },
1297 | {
1298 | "cell_type": "code",
1299 | "metadata": {
1300 | "id": "_1NJlT1DDmzB",
1301 | "colab_type": "code",
1302 | "colab": {}
1303 | },
1304 | "source": [
1305 | "set_1 - set_2"
1306 | ],
1307 | "execution_count": 0,
1308 | "outputs": []
1309 | },
1310 | {
1311 | "cell_type": "code",
1312 | "metadata": {
1313 | "id": "3L6Sy0n-Dv6x",
1314 | "colab_type": "code",
1315 | "colab": {}
1316 | },
1317 | "source": [
1318 | "set_1.difference(set_2)"
1319 | ],
1320 | "execution_count": 0,
1321 | "outputs": []
1322 | },
1323 | {
1324 | "cell_type": "markdown",
1325 | "metadata": {
1326 | "id": "2ggt6o4AFigW",
1327 | "colab_type": "text"
1328 | },
1329 | "source": [
1330 | "## set <-> list"
1331 | ]
1332 | },
1333 | {
1334 | "cell_type": "code",
1335 | "metadata": {
1336 | "id": "W3dBl4DsFm-K",
1337 | "colab_type": "code",
1338 | "colab": {}
1339 | },
1340 | "source": [
1341 | "list(set_1)"
1342 | ],
1343 | "execution_count": 0,
1344 | "outputs": []
1345 | },
1346 | {
1347 | "cell_type": "code",
1348 | "metadata": {
1349 | "id": "TG59RMUyFtwp",
1350 | "colab_type": "code",
1351 | "colab": {}
1352 | },
1353 | "source": [
1354 | "set([2, 3, 4, 2, 6, 7, 1, 5, 6])"
1355 | ],
1356 | "execution_count": 0,
1357 | "outputs": []
1358 | },
1359 | {
1360 | "cell_type": "markdown",
1361 | "metadata": {
1362 | "id": "Q8QU--j3ERD7",
1363 | "colab_type": "text"
1364 | },
1365 | "source": [
1366 | "## Need help? dir(set) or help(set)"
1367 | ]
1368 | },
1369 | {
1370 | "cell_type": "code",
1371 | "metadata": {
1372 | "id": "dj1ezoAYE_3r",
1373 | "colab_type": "code",
1374 | "colab": {}
1375 | },
1376 | "source": [
1377 | "help(set)"
1378 | ],
1379 | "execution_count": 0,
1380 | "outputs": []
1381 | },
1382 | {
1383 | "cell_type": "markdown",
1384 | "metadata": {
1385 | "id": "gV7YT_FfGj4K",
1386 | "colab_type": "text"
1387 | },
1388 | "source": [
1389 | "# Dictionary (dict)\n",
1390 | "\n",
1391 | "Dictionary in Python is an unordered collection of data value pairs"
1392 | ]
1393 | },
1394 | {
1395 | "cell_type": "code",
1396 | "metadata": {
1397 | "id": "jm6PJX3ywcDI",
1398 | "colab_type": "code",
1399 | "colab": {}
1400 | },
1401 | "source": [
1402 | "# empty dictionary\n",
1403 | "d1 = {} # d1 = dict()\n",
1404 | "\n",
1405 | "# add key-value pairs to the dictionary\n",
1406 | "d1['a'] = 12\n",
1407 | "d1['b'] = 3\n",
1408 | "d1['c'] = 47\n",
1409 | "d1['d'] = 18\n",
1410 | "\n",
1411 | "# show the dictionary\n",
1412 | "d1"
1413 | ],
1414 | "execution_count": 0,
1415 | "outputs": []
1416 | },
1417 | {
1418 | "cell_type": "code",
1419 | "metadata": {
1420 | "id": "dr-R17LVKgGW",
1421 | "colab_type": "code",
1422 | "colab": {}
1423 | },
1424 | "source": [
1425 | "# access value by key\n",
1426 | "print(d1['c'])"
1427 | ],
1428 | "execution_count": 0,
1429 | "outputs": []
1430 | },
1431 | {
1432 | "cell_type": "code",
1433 | "metadata": {
1434 | "id": "GEV041DowtqT",
1435 | "colab_type": "code",
1436 | "colab": {}
1437 | },
1438 | "source": [
1439 | "# all keys\n",
1440 | "d1.keys()"
1441 | ],
1442 | "execution_count": 0,
1443 | "outputs": []
1444 | },
1445 | {
1446 | "cell_type": "code",
1447 | "metadata": {
1448 | "id": "PLNsliYjxPF3",
1449 | "colab_type": "code",
1450 | "colab": {}
1451 | },
1452 | "source": [
1453 | "# all values\n",
1454 | "d1.values()"
1455 | ],
1456 | "execution_count": 0,
1457 | "outputs": []
1458 | },
1459 | {
1460 | "cell_type": "code",
1461 | "metadata": {
1462 | "id": "GVFtWRrCxVJx",
1463 | "colab_type": "code",
1464 | "colab": {}
1465 | },
1466 | "source": [
1467 | "for entry in d1.items():\n",
1468 | " print(entry)"
1469 | ],
1470 | "execution_count": 0,
1471 | "outputs": []
1472 | },
1473 | {
1474 | "cell_type": "code",
1475 | "metadata": {
1476 | "id": "Dji2qB0uxczm",
1477 | "colab_type": "code",
1478 | "colab": {}
1479 | },
1480 | "source": [
1481 | "for k, v in d1.items():\n",
1482 | " print('%s -> %s' % (str(k), str(v)))"
1483 | ],
1484 | "execution_count": 0,
1485 | "outputs": []
1486 | },
1487 | {
1488 | "cell_type": "markdown",
1489 | "metadata": {
1490 | "id": "FlT-YzvkaVrQ",
1491 | "colab_type": "text"
1492 | },
1493 | "source": [
1494 | "## Merge two dictionaries\n",
1495 | "update() method adds items to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value."
1496 | ]
1497 | },
1498 | {
1499 | "cell_type": "code",
1500 | "metadata": {
1501 | "id": "XB7hTMsLadrh",
1502 | "colab_type": "code",
1503 | "colab": {}
1504 | },
1505 | "source": [
1506 | "nfl_team_list_1 = {\n",
1507 | " 'Georgia': 'Atlanta Falcons',\n",
1508 | " 'New York': 'Buffalo Bills',\n",
1509 | " 'New Jersey': 'New York Giants',\n",
1510 | " 'Pennsylvania': 'Philadelphia Eagles'\n",
1511 | "}\n",
1512 | "nfl_team_list_2 = {\n",
1513 | " 'Arizona': 'Arizona Cardinals',\n",
1514 | " 'New York': 'Buffalo Bills',\n",
1515 | " 'New Jersey': 'New York Jets',\n",
1516 | " 'Pennsylvania': 'Pittsburgh Steelers',\n",
1517 | " 'Illinois': 'Chicago Bears'\n",
1518 | "}"
1519 | ],
1520 | "execution_count": 0,
1521 | "outputs": []
1522 | },
1523 | {
1524 | "cell_type": "code",
1525 | "metadata": {
1526 | "id": "mXQ7SbA7I-tR",
1527 | "colab_type": "code",
1528 | "colab": {}
1529 | },
1530 | "source": [
1531 | "nfl_team_list_1.update(nfl_team_list_2)\n",
1532 | "nfl_team_list_1"
1533 | ],
1534 | "execution_count": 0,
1535 | "outputs": []
1536 | },
1537 | {
1538 | "cell_type": "markdown",
1539 | "metadata": {
1540 | "id": "1kPSFdoE9bUz",
1541 | "colab_type": "text"
1542 | },
1543 | "source": [
1544 | "## Remove items from a dictionary"
1545 | ]
1546 | },
1547 | {
1548 | "cell_type": "code",
1549 | "metadata": {
1550 | "id": "0DP-VkuX9gbb",
1551 | "colab_type": "code",
1552 | "colab": {}
1553 | },
1554 | "source": [
1555 | "# pop() removes an item with speficifed key and returns the value\n",
1556 | "val = d1.pop('c')\n",
1557 | "print(val)\n",
1558 | "print(d1)"
1559 | ],
1560 | "execution_count": 0,
1561 | "outputs": []
1562 | },
1563 | {
1564 | "cell_type": "code",
1565 | "metadata": {
1566 | "id": "gjiqArH59gfl",
1567 | "colab_type": "code",
1568 | "colab": {}
1569 | },
1570 | "source": [
1571 | "# del\n",
1572 | "car = {\n",
1573 | " 'brand': 'Ford',\n",
1574 | " 'model': 'Explorer',\n",
1575 | " 'year': 2017,\n",
1576 | " 'price': 20000\n",
1577 | "}\n",
1578 | "car"
1579 | ],
1580 | "execution_count": 0,
1581 | "outputs": []
1582 | },
1583 | {
1584 | "cell_type": "code",
1585 | "metadata": {
1586 | "id": "W6XHJwqPZnRy",
1587 | "colab_type": "code",
1588 | "colab": {}
1589 | },
1590 | "source": [
1591 | "# del keyword delete item by key\n",
1592 | "del car['price']\n",
1593 | "print(car)"
1594 | ],
1595 | "execution_count": 0,
1596 | "outputs": []
1597 | },
1598 | {
1599 | "cell_type": "markdown",
1600 | "metadata": {
1601 | "id": "IrVjRyN-xxyI",
1602 | "colab_type": "text"
1603 | },
1604 | "source": [
1605 | "## Dictionary comprehension"
1606 | ]
1607 | },
1608 | {
1609 | "cell_type": "code",
1610 | "metadata": {
1611 | "id": "us-Ugq2tG0bX",
1612 | "colab_type": "code",
1613 | "colab": {}
1614 | },
1615 | "source": [
1616 | "d1 = {'a': 12, 'b': 3, 'c': 47, 'd': 18}\n",
1617 | "d1"
1618 | ],
1619 | "execution_count": 0,
1620 | "outputs": []
1621 | },
1622 | {
1623 | "cell_type": "code",
1624 | "metadata": {
1625 | "id": "oLZIfgEIwEQG",
1626 | "colab_type": "code",
1627 | "colab": {}
1628 | },
1629 | "source": [
1630 | "# inverting a dictionary\n",
1631 | "d1_inverted = { v: k for k, v in d1.items() }\n",
1632 | "d1_inverted"
1633 | ],
1634 | "execution_count": 0,
1635 | "outputs": []
1636 | },
1637 | {
1638 | "cell_type": "code",
1639 | "metadata": {
1640 | "id": "X_Vv3Tz2zEJR",
1641 | "colab_type": "code",
1642 | "colab": {}
1643 | },
1644 | "source": [
1645 | "# double all values in d1\n",
1646 | "{ k: v*2 for k, v in d1.items() }"
1647 | ],
1648 | "execution_count": 0,
1649 | "outputs": []
1650 | },
1651 | {
1652 | "cell_type": "markdown",
1653 | "metadata": {
1654 | "id": "sn5dvptrwLD1",
1655 | "colab_type": "text"
1656 | },
1657 | "source": [
1658 | ""
1659 | ]
1660 | },
1661 | {
1662 | "cell_type": "markdown",
1663 | "metadata": {
1664 | "id": "5F6noeY4HiEV",
1665 | "colab_type": "text"
1666 | },
1667 | "source": [
1668 | "# More Examples"
1669 | ]
1670 | },
1671 | {
1672 | "cell_type": "code",
1673 | "metadata": {
1674 | "id": "JGPD3X1vHiiJ",
1675 | "colab_type": "code",
1676 | "colab": {}
1677 | },
1678 | "source": [
1679 | "state_list = [\n",
1680 | " {\n",
1681 | " 'State': 'NJ',\n",
1682 | " 'Capital': 'Trenton',\n",
1683 | " 'Population': 9000000,\n",
1684 | " 'Cities': ['Newark', 'Jersey City', 'Paterson']\n",
1685 | " },\n",
1686 | " {\n",
1687 | " 'State': 'NY',\n",
1688 | " 'Capital': 'Albany',\n",
1689 | " 'Population': 20000000,\n",
1690 | " 'Cities': ['New York', 'Buffalo', 'Rochester']\n",
1691 | " },\n",
1692 | " {\n",
1693 | " 'State': 'PA',\n",
1694 | " 'Capital': 'Harrisburg',\n",
1695 | " 'Population': 13000000,\n",
1696 | " 'Cities': ['Philadelphia', 'Pittsburgh', 'Allentown']\n",
1697 | " } \n",
1698 | "]"
1699 | ],
1700 | "execution_count": 0,
1701 | "outputs": []
1702 | },
1703 | {
1704 | "cell_type": "code",
1705 | "metadata": {
1706 | "id": "iCLvUPBVvnK4",
1707 | "colab_type": "code",
1708 | "colab": {}
1709 | },
1710 | "source": [
1711 | "state_list[2]['Cities']"
1712 | ],
1713 | "execution_count": 0,
1714 | "outputs": []
1715 | },
1716 | {
1717 | "cell_type": "code",
1718 | "metadata": {
1719 | "id": "nA_UFVMyd_eE",
1720 | "colab_type": "code",
1721 | "colab": {}
1722 | },
1723 | "source": [
1724 | "state_dict = {\n",
1725 | " 'NY': {\n",
1726 | " 'Capital': 'Albany',\n",
1727 | " 'Population': 20000000,\n",
1728 | " 'Cities': ['New York', 'Buffalo', 'Rochester']\n",
1729 | " },\n",
1730 | " 'NJ': {\n",
1731 | " 'Capital': 'Trenton',\n",
1732 | " 'Population': 9000000,\n",
1733 | " 'Cities': ['Newark', 'Jersey City', 'Paterson']\n",
1734 | " },\n",
1735 | " 'PA': {\n",
1736 | " 'Capital': 'Harrisburg',\n",
1737 | " 'Population': 13000000,\n",
1738 | " 'Cities': ['Philadelphia', 'Pittsburgh', 'Allentown']\n",
1739 | " }\n",
1740 | "}"
1741 | ],
1742 | "execution_count": 0,
1743 | "outputs": []
1744 | },
1745 | {
1746 | "cell_type": "code",
1747 | "metadata": {
1748 | "id": "22dXLkknu2Z1",
1749 | "colab_type": "code",
1750 | "colab": {}
1751 | },
1752 | "source": [
1753 | "state_dict['NY']"
1754 | ],
1755 | "execution_count": 0,
1756 | "outputs": []
1757 | },
1758 | {
1759 | "cell_type": "code",
1760 | "metadata": {
1761 | "id": "IcPZSwiIuknl",
1762 | "colab_type": "code",
1763 | "colab": {}
1764 | },
1765 | "source": [
1766 | "state_dict['NY']['Cities'][0]"
1767 | ],
1768 | "execution_count": 0,
1769 | "outputs": []
1770 | },
1771 | {
1772 | "cell_type": "markdown",
1773 | "metadata": {
1774 | "id": "9qatZ3AfBi9y",
1775 | "colab_type": "text"
1776 | },
1777 | "source": [
1778 | "### Practice Problems:"
1779 | ]
1780 | },
1781 | {
1782 | "cell_type": "markdown",
1783 | "metadata": {
1784 | "id": "CVIq4W53BoWN",
1785 | "colab_type": "text"
1786 | },
1787 | "source": [
1788 | "1. write a program that returns a list that contains only the elements that are common between two lists "
1789 | ]
1790 | },
1791 | {
1792 | "cell_type": "code",
1793 | "metadata": {
1794 | "id": "eIlZOJv4Bo-5",
1795 | "colab_type": "code",
1796 | "colab": {}
1797 | },
1798 | "source": [
1799 | "list1 = [3, 4, 5, 6, 2, 1, 4, 9, 0, -2, 7]\n",
1800 | "list2 = [-3, 8, 5, 6, 2, 1, -5, 9, 12, -2, 11]\n",
1801 | "\n",
1802 | "def common_list(l1, l2):\n",
1803 | " pass # your code here\n",
1804 | "\n",
1805 | "print(common_list(list1, list2))\n"
1806 | ],
1807 | "execution_count": 0,
1808 | "outputs": []
1809 | },
1810 | {
1811 | "cell_type": "markdown",
1812 | "metadata": {
1813 | "id": "0es0GNBgBqMp",
1814 | "colab_type": "text"
1815 | },
1816 | "source": [
1817 | "2. Write a function that takes a list of numbers and returns the minimum and maximum numbers as a tuple. "
1818 | ]
1819 | },
1820 | {
1821 | "cell_type": "code",
1822 | "metadata": {
1823 | "id": "4WZlmsrUB8rc",
1824 | "colab_type": "code",
1825 | "colab": {}
1826 | },
1827 | "source": [
1828 | "num_list = [3, 4, 5, 6, 2, 1, 4, 9, 0, -2, 7]\n",
1829 | "\n",
1830 | "def min_max(n_list):\n",
1831 | " pass # your code here\n",
1832 | "\n",
1833 | "print(min_max(num_list))\n"
1834 | ],
1835 | "execution_count": 0,
1836 | "outputs": []
1837 | },
1838 | {
1839 | "cell_type": "markdown",
1840 | "metadata": {
1841 | "id": "RKSqpr6OCCbN",
1842 | "colab_type": "text"
1843 | },
1844 | "source": [
1845 | "3. Write a function to generate the first 10 Fibonacci numbers and return the numers in a list\n",
1846 | "\n",
1847 | "$F_n = F_{n-1} + F_{n-2}$\n",
1848 | "\n",
1849 | "$F_0 = 0$\n",
1850 | "\n",
1851 | "$F_1 = 1$"
1852 | ]
1853 | },
1854 | {
1855 | "cell_type": "code",
1856 | "metadata": {
1857 | "id": "1pgDfONKCLsS",
1858 | "colab_type": "code",
1859 | "colab": {}
1860 | },
1861 | "source": [
1862 | "def fibonacci_numbers(up_to=10):\n",
1863 | " # first two fibonacci numbers\n",
1864 | " fibs = [0, 1]\n",
1865 | " \n",
1866 | " pass # your code here\n",
1867 | "\n",
1868 | "print(fibonacci_numbers())"
1869 | ],
1870 | "execution_count": 0,
1871 | "outputs": []
1872 | },
1873 | {
1874 | "cell_type": "markdown",
1875 | "metadata": {
1876 | "id": "xCRuUv0tDRyd",
1877 | "colab_type": "text"
1878 | },
1879 | "source": [
1880 | "4. Write a function to reverse a string ( Friday -> yadirF)"
1881 | ]
1882 | },
1883 | {
1884 | "cell_type": "code",
1885 | "metadata": {
1886 | "id": "Mnq5eH65DZEN",
1887 | "colab_type": "code",
1888 | "colab": {}
1889 | },
1890 | "source": [
1891 | "def reverse_string(str):\n",
1892 | "\n",
1893 | " pass # your code here\n",
1894 | "\n",
1895 | "print(reverse_string('Friday'))"
1896 | ],
1897 | "execution_count": 0,
1898 | "outputs": []
1899 | },
1900 | {
1901 | "cell_type": "markdown",
1902 | "metadata": {
1903 | "id": "Z68RXcuVDbre",
1904 | "colab_type": "text"
1905 | },
1906 | "source": [
1907 | "5. Write a function to reverse word order of a string containing multiple words. For example: Tom chases Jerry -> Jerry chases Tom"
1908 | ]
1909 | },
1910 | {
1911 | "cell_type": "code",
1912 | "metadata": {
1913 | "id": "9wSwjCerD8d9",
1914 | "colab_type": "code",
1915 | "colab": {}
1916 | },
1917 | "source": [
1918 | "def reverse_words(str):\n",
1919 | "\n",
1920 | " pass # your code here\n",
1921 | "\n",
1922 | "str1 = 'Tom chases Jerry'\n",
1923 | "print(reverse_words(str1))"
1924 | ],
1925 | "execution_count": 0,
1926 | "outputs": []
1927 | },
1928 | {
1929 | "cell_type": "markdown",
1930 | "metadata": {
1931 | "id": "62OQOTQs0k5K",
1932 | "colab_type": "text"
1933 | },
1934 | "source": [
1935 | "6. Given a list of stock records, find out the total number of shares for each stock.\n",
1936 | "\n",
1937 | "Symbol, Price, Shares
\n",
1938 | "IBM, 142.3, 50
\n",
1939 | "MSFT, 170.21, 100
\n",
1940 | "GOOG, 1469.32, 15
\n",
1941 | "IBM, 142.3, 20
\n",
1942 | "C, 74.78, 100
\n",
1943 | "CAT, 133.73, 80
\n",
1944 | "C, 74.78, 200
\n",
1945 | "GOOG, 1469.32, 7
\n",
1946 | "C, 74.78, 80
"
1947 | ]
1948 | },
1949 | {
1950 | "cell_type": "code",
1951 | "metadata": {
1952 | "id": "5Syn67Lzzsl2",
1953 | "colab_type": "code",
1954 | "colab": {}
1955 | },
1956 | "source": [
1957 | ""
1958 | ],
1959 | "execution_count": 0,
1960 | "outputs": []
1961 | },
1962 | {
1963 | "cell_type": "markdown",
1964 | "metadata": {
1965 | "id": "hi5vnh-p8J1Y",
1966 | "colab_type": "text"
1967 | },
1968 | "source": [
1969 | "7. Given a list of stock buy/sell records, find out net values for each stock, and the total net value\n",
1970 | "\n",
1971 | "Symbol, Price, Shares, Buy/Sell
\n",
1972 | "IBM, 142.3, 50, Buy
\n",
1973 | "MSFT, 170.21, 100, Buy
\n",
1974 | "GOOG, 1469.32, 15, Buy
\n",
1975 | "IBM, 142.3, 20, Sell
\n",
1976 | "C, 74.78, 100, Buy
\n",
1977 | "CAT, 133.73, 80, Buy
\n",
1978 | "C, 74.78, 200, Buy
\n",
1979 | "GOOG, 1469.32, 7, Sell
\n",
1980 | "C, 74.78, 80, Sell
"
1981 | ]
1982 | },
1983 | {
1984 | "cell_type": "code",
1985 | "metadata": {
1986 | "id": "IHOG8kbF8ucE",
1987 | "colab_type": "code",
1988 | "colab": {}
1989 | },
1990 | "source": [
1991 | ""
1992 | ],
1993 | "execution_count": 0,
1994 | "outputs": []
1995 | }
1996 | ]
1997 | }
--------------------------------------------------------------------------------
/2_python_file_handling.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "hKCc0gncbfHC"
8 | },
9 | "source": [
10 | "### **Pre-requisities for this class. Please execute this cell before starting the class**"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": 1,
16 | "metadata": {
17 | "colab": {},
18 | "colab_type": "code",
19 | "id": "bcVyRdN6biFX"
20 | },
21 | "outputs": [],
22 | "source": [
23 | "def write_file(file_name,content):\n",
24 | " with open(file_name,\"w\") as f:\n",
25 | " f.write(content)\n",
26 | "\n",
27 | "text = '''Teacher: Why are you late, raghu?\n",
28 | "Raghu: Because of the sign\n",
29 | "Teacher: What sign?\n",
30 | "Raghu: The one that says \"School Ahead, Go slow\"'''\n",
31 | "write_file(\"funny.txt\",text)\n",
32 | "\n",
33 | "text='''Two roads diverged in a yellow wood,\n",
34 | "And sorry I could not travel both\n",
35 | "And be one traveler, long I stood\n",
36 | "And looked down one as far as I could\n",
37 | "To where it bent in the undergrowth;\n",
38 | "\n",
39 | "Then took the other, as just as fair,\n",
40 | "And having perhaps the better claim,\n",
41 | "Because it was grassy and wanted wear;\n",
42 | "Though as for that the passing there\n",
43 | "Had worn them really about the same,\n",
44 | "\n",
45 | "And both that morning equally lay\n",
46 | "In leaves no step had trodden black.\n",
47 | "Oh, I kept the first for another day!\n",
48 | "Yet knowing how way leads on to way,\n",
49 | "I doubted if I should ever come back.\n",
50 | "\n",
51 | "I shall be telling this with a sigh\n",
52 | "Somewhere ages and ages hence:\n",
53 | "Two roads diverged in a wood, and I—\n",
54 | "I took the one less traveled by,\n",
55 | "And that has made all the difference.'''\n",
56 | "write_file(\"poem.txt\",text)\n",
57 | "\n",
58 | "text='''rohit,9\n",
59 | "shakib,56\n",
60 | "babar,56\n",
61 | "rohit,120\n",
62 | "rohit,105\n",
63 | "shakib,78\n",
64 | "rohit,140\n",
65 | "babar,45\n",
66 | "rohit,130\n",
67 | "shakib,102\n",
68 | "babar,120\n",
69 | "babar,5\n",
70 | "shakib,72\n",
71 | "babar,67'''\n",
72 | "write_file(\"scores.csv\",text)\n",
73 | "\n",
74 | "text='''Company Name,Price,Earnings Per Share, Book Value\n",
75 | "Reliance,1467,66,653\n",
76 | "Tata Steel,391,89,572\n",
77 | "Infosys,650,35,147\n",
78 | "Axis Bank,739,19,263\n",
79 | "Bajaj Finance,4044,69,341'''\n",
80 | "write_file(\"stocks.csv\",text)"
81 | ]
82 | },
83 | {
84 | "cell_type": "markdown",
85 | "metadata": {
86 | "colab_type": "text",
87 | "id": "f53OjP3Q6Cea"
88 | },
89 | "source": [
90 | "### **Reading a text file**\n"
91 | ]
92 | },
93 | {
94 | "cell_type": "code",
95 | "execution_count": 3,
96 | "metadata": {
97 | "colab": {
98 | "base_uri": "https://localhost:8080/",
99 | "height": 137
100 | },
101 | "colab_type": "code",
102 | "id": "VmsYaI0VlUCa",
103 | "outputId": "4e57ce91-dc37-4944-bae0-cbb316308e1d"
104 | },
105 | "outputs": [
106 | {
107 | "name": "stdout",
108 | "output_type": "stream",
109 | "text": [
110 | "Teacher: Why are you late, raghu?\n",
111 | "\n",
112 | "Raghu: Because of the sign\n",
113 | "\n",
114 | "Teacher: What sign?\n",
115 | "\n",
116 | "Raghu: The one that says \"School Ahead, Go slow\"\n"
117 | ]
118 | }
119 | ],
120 | "source": [
121 | "f=open(\"funny.txt\",\"r\")\n",
122 | "for line in f:\n",
123 | " print(line)\n",
124 | "f.close()"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {
130 | "colab_type": "text",
131 | "id": "dUKdbaVZ6V6A"
132 | },
133 | "source": [
134 | "### **Using readlines() function to read all lines into a list**"
135 | ]
136 | },
137 | {
138 | "cell_type": "code",
139 | "execution_count": 2,
140 | "metadata": {
141 | "colab": {
142 | "base_uri": "https://localhost:8080/",
143 | "height": 54
144 | },
145 | "colab_type": "code",
146 | "id": "nZYcodV2wJmj",
147 | "outputId": "a74119e7-190b-410e-c694-e2176e44c51b"
148 | },
149 | "outputs": [
150 | {
151 | "name": "stdout",
152 | "output_type": "stream",
153 | "text": [
154 | "['Teacher: Why are you late, raghu?\\n', 'Raghu: Because of the sign\\n', 'Teacher: What sign?\\n', 'Raghu: The one that says \"School Ahead, Go slow\"']\n"
155 | ]
156 | }
157 | ],
158 | "source": [
159 | "f=open(\"funny.txt\",\"r\")\n",
160 | "lines = f.readlines()\n",
161 | "print(lines)\n",
162 | "f.close()"
163 | ]
164 | },
165 | {
166 | "cell_type": "markdown",
167 | "metadata": {
168 | "colab_type": "text",
169 | "id": "osfegWId6j4Y"
170 | },
171 | "source": [
172 | "### **Write file**"
173 | ]
174 | },
175 | {
176 | "cell_type": "code",
177 | "execution_count": 4,
178 | "metadata": {
179 | "colab": {},
180 | "colab_type": "code",
181 | "id": "2nDjFdVV6pCx"
182 | },
183 | "outputs": [],
184 | "source": [
185 | "f=open(\"love.txt\",\"w\")\n",
186 | "f.write(\"I love python\")\n",
187 | "f.close()"
188 | ]
189 | },
190 | {
191 | "cell_type": "code",
192 | "execution_count": 5,
193 | "metadata": {
194 | "colab": {},
195 | "colab_type": "code",
196 | "id": "xJEgGKRL7Kh7"
197 | },
198 | "outputs": [],
199 | "source": [
200 | "f=open(\"love.txt\",\"w\")\n",
201 | "f.write(\"I love javascript\")\n",
202 | "f.close()"
203 | ]
204 | },
205 | {
206 | "cell_type": "markdown",
207 | "metadata": {
208 | "colab_type": "text",
209 | "id": "EoCtd5yD7SHY"
210 | },
211 | "source": [
212 | "### **Using append mode to avoid overwriting existing file content**"
213 | ]
214 | },
215 | {
216 | "cell_type": "code",
217 | "execution_count": 6,
218 | "metadata": {
219 | "colab": {},
220 | "colab_type": "code",
221 | "id": "hjZEwAWf7XSm"
222 | },
223 | "outputs": [],
224 | "source": [
225 | "# You can use append mode to stop having previous lines overwritten\n",
226 | "f=open(\"love.txt\",\"a\")\n",
227 | "f.write(\"I love python\")\n",
228 | "f.close()"
229 | ]
230 | },
231 | {
232 | "cell_type": "markdown",
233 | "metadata": {
234 | "colab_type": "text",
235 | "id": "0HBzDzIc7jhL"
236 | },
237 | "source": [
238 | "### **writelines to write multiple lines in one shot**"
239 | ]
240 | },
241 | {
242 | "cell_type": "code",
243 | "execution_count": 7,
244 | "metadata": {
245 | "colab": {},
246 | "colab_type": "code",
247 | "id": "B_Ymbl1G7rgy"
248 | },
249 | "outputs": [],
250 | "source": [
251 | "f=open(\"love.txt\",\"w\")\n",
252 | "f.writelines([\"I love C++\\n\",\"I love scala\"])\n",
253 | "f.close()"
254 | ]
255 | },
256 | {
257 | "cell_type": "markdown",
258 | "metadata": {
259 | "colab_type": "text",
260 | "id": "aNlwrDQx7wUj"
261 | },
262 | "source": [
263 | "### **With statement**"
264 | ]
265 | },
266 | {
267 | "cell_type": "markdown",
268 | "metadata": {
269 | "colab_type": "text",
270 | "id": "eyBsetSAb2bP"
271 | },
272 | "source": [
273 | "In previous lines of code every time you open a file you need to close it by calling .close(). Closing file takes care of resource cleanup etc. Alternatively we can use with statement which will take care of closing file so you don't have to do it explicitly. Below code snippet shows how to use with statement for file handling."
274 | ]
275 | },
276 | {
277 | "cell_type": "code",
278 | "execution_count": 8,
279 | "metadata": {
280 | "colab": {
281 | "base_uri": "https://localhost:8080/",
282 | "height": 137
283 | },
284 | "colab_type": "code",
285 | "id": "BYbMgK2z7ziZ",
286 | "outputId": "0d8c0f94-76ef-4007-c174-15b660c8bab3"
287 | },
288 | "outputs": [
289 | {
290 | "name": "stdout",
291 | "output_type": "stream",
292 | "text": [
293 | "Teacher: Why are you late, raghu?\n",
294 | "\n",
295 | "Raghu: Because of the sign\n",
296 | "\n",
297 | "Teacher: What sign?\n",
298 | "\n",
299 | "Raghu: The one that says \"School Ahead, Go slow\"\n"
300 | ]
301 | }
302 | ],
303 | "source": [
304 | "with open(\"funny.txt\",\"r\") as f:\n",
305 | " for line in f:\n",
306 | " print(line)"
307 | ]
308 | },
309 | {
310 | "cell_type": "markdown",
311 | "metadata": {
312 | "colab_type": "text",
313 | "id": "NnIMZgVZ73Cr"
314 | },
315 | "source": [
316 | "### **Cricket score analytics project**"
317 | ]
318 | },
319 | {
320 | "cell_type": "markdown",
321 | "metadata": {
322 | "colab_type": "text",
323 | "id": "6doXKQf-8IRq"
324 | },
325 | "source": [
326 | "Cricket world cup scores for individual players are given in scores.csv file in below format. \n",
327 | "\n",
328 | "|player name|score|\n",
329 | "|-----------|-----|\n",
330 | "|rohit|9|\n",
331 | "|sakib|56|\n",
332 | "|babar|56|\n",
333 | "|rohit|120|\n",
334 | "|rohit|105|\n",
335 | "|shakib|78|\n",
336 | "\n",
337 | "You need to find out min, max and average score for every player."
338 | ]
339 | },
340 | {
341 | "cell_type": "code",
342 | "execution_count": 9,
343 | "metadata": {
344 | "colab": {
345 | "base_uri": "https://localhost:8080/",
346 | "height": 34
347 | },
348 | "colab_type": "code",
349 | "id": "C38vMObt8u7b",
350 | "outputId": "2d6d9218-59ca-4e25-8e59-f24f44f7824d"
351 | },
352 | "outputs": [
353 | {
354 | "name": "stdout",
355 | "output_type": "stream",
356 | "text": [
357 | "{'rohit': [9, 120, 105, 140, 130], 'shakib': [56, 78, 102, 72], 'babar': [56, 45, 120, 5, 67]}\n"
358 | ]
359 | }
360 | ],
361 | "source": [
362 | "player_scores = {}\n",
363 | "with open(\"scores.csv\",\"r\") as f:\n",
364 | " for line in f:\n",
365 | " tokens = line.split(',')\n",
366 | " player = tokens[0]\n",
367 | " score = int(tokens[1])\n",
368 | " if player in player_scores:\n",
369 | " player_scores[player].append(score)\n",
370 | " else:\n",
371 | " player_scores[player] = [score]\n",
372 | "\n",
373 | "print(player_scores)"
374 | ]
375 | },
376 | {
377 | "cell_type": "code",
378 | "execution_count": 10,
379 | "metadata": {
380 | "colab": {
381 | "base_uri": "https://localhost:8080/",
382 | "height": 68
383 | },
384 | "colab_type": "code",
385 | "id": "1vr2mNYx9LzM",
386 | "outputId": "cf9b4586-865d-4869-cee7-4d8d7c43db05"
387 | },
388 | "outputs": [
389 | {
390 | "name": "stdout",
391 | "output_type": "stream",
392 | "text": [
393 | "rohit==>Min:9, Max:140, Avg:100.8\n",
394 | "shakib==>Min:56, Max:102, Avg:77.0\n",
395 | "babar==>Min:5, Max:120, Avg:58.6\n"
396 | ]
397 | }
398 | ],
399 | "source": [
400 | "for player, score_list in player_scores.items():\n",
401 | " min_score=min(score_list)\n",
402 | " max_score=max(score_list)\n",
403 | " avg_score=sum(score_list)/len(score_list)\n",
404 | "\n",
405 | " print(f\"{player}==>Min:{min_score}, Max:{max_score}, Avg:{avg_score}\")"
406 | ]
407 | },
408 | {
409 | "cell_type": "markdown",
410 | "metadata": {
411 | "colab_type": "text",
412 | "id": "HqGkzGcV-Ylv"
413 | },
414 | "source": [
415 | "# **Exercise**"
416 | ]
417 | },
418 | {
419 | "cell_type": "markdown",
420 | "metadata": {
421 | "colab_type": "text",
422 | "id": "_JrYr4Nx-f9t"
423 | },
424 | "source": [
425 | "(1) **poem.txt** contains famous poem \"Road not taken\" by poet Robert Frost. You have to read this file in your python program and find out words with maximum occurance."
426 | ]
427 | },
428 | {
429 | "cell_type": "markdown",
430 | "metadata": {
431 | "colab_type": "text",
432 | "id": "h8xJ7cUK-rO1"
433 | },
434 | "source": [
435 | "(2) **stocks.csv** contains stock price, earnings per share and book value. You are writing a stock market application that will process this file and create a new file with financial metrics such as pe ratio and price to book ratio. These are calculated as,\n",
436 | "\n",
437 | "```\n",
438 | "pe ratio = price / earnings per share\n",
439 | "price to book ratio = price / book value\n",
440 | "```\n",
441 | "Your input format (stocks.csv) is,\n",
442 | "\n",
443 | "\n",
444 | "|Company Name|Price|Earnings Per Share|Book Value|\n",
445 | "|-------|----------|-------|----------|\n",
446 | "|Reliance|1467|66|653|\n",
447 | "|Tata Steel|391|89|572|\n",
448 | "\n",
449 | "\n",
450 | "Output.csv should look like this,\n",
451 | "\n",
452 | "\n",
453 | "|Company Name|PE Ratio|PB Ratio|\n",
454 | "|-------|----------|-------|\n",
455 | "|Reliance|22.23|2.25|\n",
456 | "|Tata Steel|4.39|0.68|\n"
457 | ]
458 | }
459 | ],
460 | "metadata": {
461 | "colab": {
462 | "collapsed_sections": [],
463 | "name": "python_file_handling.ipynb",
464 | "provenance": []
465 | },
466 | "kernelspec": {
467 | "display_name": "Python 3",
468 | "language": "python",
469 | "name": "python3"
470 | },
471 | "language_info": {
472 | "codemirror_mode": {
473 | "name": "ipython",
474 | "version": 3
475 | },
476 | "file_extension": ".py",
477 | "mimetype": "text/x-python",
478 | "name": "python",
479 | "nbconvert_exporter": "python",
480 | "pygments_lexer": "ipython3",
481 | "version": "3.7.3"
482 | }
483 | },
484 | "nbformat": 4,
485 | "nbformat_minor": 1
486 | }
487 |
--------------------------------------------------------------------------------
/3_exception_handling.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "m9uJyhSjcOI-"
8 | },
9 | "source": [
10 | "#**Exception Handlilng In Python**"
11 | ]
12 | },
13 | {
14 | "cell_type": "code",
15 | "execution_count": 0,
16 | "metadata": {
17 | "colab": {},
18 | "colab_type": "code",
19 | "id": "tsCcaY2NcKPE"
20 | },
21 | "outputs": [],
22 | "source": [
23 | "def divide_numbers(a,b):\n",
24 | " return a/b"
25 | ]
26 | },
27 | {
28 | "cell_type": "code",
29 | "execution_count": 0,
30 | "metadata": {
31 | "colab": {
32 | "base_uri": "https://localhost:8080/",
33 | "height": 34
34 | },
35 | "colab_type": "code",
36 | "id": "5MoaYoy0cSTl",
37 | "outputId": "2043e88d-ed00-4100-9112-f1966c75a216"
38 | },
39 | "outputs": [
40 | {
41 | "data": {
42 | "text/plain": [
43 | "5.0"
44 | ]
45 | },
46 | "execution_count": 2,
47 | "metadata": {
48 | "tags": []
49 | },
50 | "output_type": "execute_result"
51 | }
52 | ],
53 | "source": [
54 | "divide_numbers(10,2)"
55 | ]
56 | },
57 | {
58 | "cell_type": "code",
59 | "execution_count": 0,
60 | "metadata": {
61 | "colab": {
62 | "base_uri": "https://localhost:8080/",
63 | "height": 233
64 | },
65 | "colab_type": "code",
66 | "id": "pUgT4pjvcTlW",
67 | "outputId": "967877bc-2d54-4651-b743-1b50f7d8b8b7"
68 | },
69 | "outputs": [
70 | {
71 | "ename": "ZeroDivisionError",
72 | "evalue": "ignored",
73 | "output_type": "error",
74 | "traceback": [
75 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
76 | "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)",
77 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdivide_numbers\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
78 | "\u001b[0;32m\u001b[0m in \u001b[0;36mdivide_numbers\u001b[0;34m(a, b)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdivide_numbers\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
79 | "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
80 | ]
81 | }
82 | ],
83 | "source": [
84 | "divide_numbers(10,0)"
85 | ]
86 | },
87 | {
88 | "cell_type": "markdown",
89 | "metadata": {
90 | "colab_type": "text",
91 | "id": "I5m5FdAqcYC2"
92 | },
93 | "source": [
94 | "**Now let's handle the exception in our function**"
95 | ]
96 | },
97 | {
98 | "cell_type": "code",
99 | "execution_count": 1,
100 | "metadata": {
101 | "colab": {},
102 | "colab_type": "code",
103 | "id": "bd9D7e_TcXE2"
104 | },
105 | "outputs": [],
106 | "source": [
107 | "def divide_numbers(a,b):\n",
108 | " try:\n",
109 | " d = a/b\n",
110 | " except ZeroDivisionError as e:\n",
111 | " print(e)\n",
112 | " d = None\n",
113 | " return d"
114 | ]
115 | },
116 | {
117 | "cell_type": "code",
118 | "execution_count": 2,
119 | "metadata": {
120 | "colab": {
121 | "base_uri": "https://localhost:8080/",
122 | "height": 34
123 | },
124 | "colab_type": "code",
125 | "id": "kwaXnur5cdO2",
126 | "outputId": "50770cfc-e74e-4cbe-c10d-8cbfec492f2f"
127 | },
128 | "outputs": [
129 | {
130 | "name": "stdout",
131 | "output_type": "stream",
132 | "text": [
133 | "division by zero\n"
134 | ]
135 | }
136 | ],
137 | "source": [
138 | "divide_numbers(10,0)"
139 | ]
140 | },
141 | {
142 | "cell_type": "markdown",
143 | "metadata": {
144 | "colab_type": "text",
145 | "id": "z2i7SZqxchWJ"
146 | },
147 | "source": [
148 | "### **Handling multiple exceptions**"
149 | ]
150 | },
151 | {
152 | "cell_type": "code",
153 | "execution_count": 0,
154 | "metadata": {
155 | "colab": {
156 | "base_uri": "https://localhost:8080/",
157 | "height": 353
158 | },
159 | "colab_type": "code",
160 | "id": "F5qw7hvZcfVO",
161 | "outputId": "bf9bcf8c-1ae2-44cc-d3e7-a530d5a9bf03"
162 | },
163 | "outputs": [
164 | {
165 | "name": "stdout",
166 | "output_type": "stream",
167 | "text": [
168 | "Enter number 1:10\n",
169 | "Enter number 2:5\n"
170 | ]
171 | },
172 | {
173 | "ename": "TypeError",
174 | "evalue": "ignored",
175 | "output_type": "error",
176 | "traceback": [
177 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
178 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
179 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Enter number 1:\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0my\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Enter number 2:\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mdivide_numbers\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
180 | "\u001b[0;32m\u001b[0m in \u001b[0;36mdivide_numbers\u001b[0;34m(a, b)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mdivide_numbers\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0md\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mZeroDivisionError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
181 | "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'str'"
182 | ]
183 | }
184 | ],
185 | "source": [
186 | "x=input(\"Enter number 1:\")\n",
187 | "y=input(\"Enter number 2:\")\n",
188 | "divide_numbers(x,y)"
189 | ]
190 | },
191 | {
192 | "cell_type": "code",
193 | "execution_count": 0,
194 | "metadata": {
195 | "colab": {},
196 | "colab_type": "code",
197 | "id": "D3ErIlgdcoDf"
198 | },
199 | "outputs": [],
200 | "source": [
201 | "def divide_numbers(a,b):\n",
202 | " try:\n",
203 | " d = a/b\n",
204 | " except TypeError as e:\n",
205 | " print(e)\n",
206 | " d = None\n",
207 | " except ZeroDivisionError as e:\n",
208 | " print(e)\n",
209 | " d = None"
210 | ]
211 | },
212 | {
213 | "cell_type": "code",
214 | "execution_count": 0,
215 | "metadata": {
216 | "colab": {
217 | "base_uri": "https://localhost:8080/",
218 | "height": 68
219 | },
220 | "colab_type": "code",
221 | "id": "bxlY5DsAco2_",
222 | "outputId": "288631e1-fe9a-4b00-dc79-60c23c87da11"
223 | },
224 | "outputs": [
225 | {
226 | "name": "stdout",
227 | "output_type": "stream",
228 | "text": [
229 | "Enter number 1:10\n",
230 | "Enter number 2:5\n",
231 | "unsupported operand type(s) for /: 'str' and 'str'\n"
232 | ]
233 | }
234 | ],
235 | "source": [
236 | "x=input(\"Enter number 1:\")\n",
237 | "y=input(\"Enter number 2:\")\n",
238 | "divide_numbers(x,y)"
239 | ]
240 | },
241 | {
242 | "cell_type": "markdown",
243 | "metadata": {
244 | "colab_type": "text",
245 | "id": "NN_9JH7ScuHO"
246 | },
247 | "source": [
248 | "### **Let's make our function fully functional**"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": 0,
254 | "metadata": {
255 | "colab": {},
256 | "colab_type": "code",
257 | "id": "Au5dYzf0cvJ2"
258 | },
259 | "outputs": [],
260 | "source": [
261 | "def divide_numbers(a,b):\n",
262 | " try:\n",
263 | " d = float(a)/float(b)\n",
264 | " except TypeError as e:\n",
265 | " print(e)\n",
266 | " d = None\n",
267 | " except ZeroDivisionError as e:\n",
268 | " print(e)\n",
269 | " d = None\n",
270 | " return d"
271 | ]
272 | },
273 | {
274 | "cell_type": "code",
275 | "execution_count": 0,
276 | "metadata": {
277 | "colab": {
278 | "base_uri": "https://localhost:8080/",
279 | "height": 68
280 | },
281 | "colab_type": "code",
282 | "id": "_V9nZB5ycxEW",
283 | "outputId": "e438eaf4-c5c0-40da-f47e-cb52d470cebb"
284 | },
285 | "outputs": [
286 | {
287 | "name": "stdout",
288 | "output_type": "stream",
289 | "text": [
290 | "Enter number 1:10\n",
291 | "Enter number 2:4\n",
292 | "2.5\n"
293 | ]
294 | }
295 | ],
296 | "source": [
297 | "x=input(\"Enter number 1:\")\n",
298 | "y=input(\"Enter number 2:\")\n",
299 | "print(divide_numbers(x,y))"
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {
305 | "colab_type": "text",
306 | "id": "OvJFYYe6c0av"
307 | },
308 | "source": [
309 | "### **Catching all exceptions**"
310 | ]
311 | },
312 | {
313 | "cell_type": "code",
314 | "execution_count": 0,
315 | "metadata": {
316 | "colab": {},
317 | "colab_type": "code",
318 | "id": "jpvT7UiZczse"
319 | },
320 | "outputs": [],
321 | "source": [
322 | "def divide_numbers(a,b):\n",
323 | " try:\n",
324 | " d = float(a)/float(b)\n",
325 | " except Exception as e:\n",
326 | " print(\"Exception occured!\")\n",
327 | " d = None\n",
328 | " return d"
329 | ]
330 | },
331 | {
332 | "cell_type": "code",
333 | "execution_count": 0,
334 | "metadata": {
335 | "colab": {
336 | "base_uri": "https://localhost:8080/",
337 | "height": 34
338 | },
339 | "colab_type": "code",
340 | "id": "2-DUM16ic4iG",
341 | "outputId": "47f719a4-07a6-4e60-d41e-d5276aaa62b1"
342 | },
343 | "outputs": [
344 | {
345 | "name": "stdout",
346 | "output_type": "stream",
347 | "text": [
348 | "Exception occured!\n"
349 | ]
350 | }
351 | ],
352 | "source": [
353 | "divide_numbers(10,0)"
354 | ]
355 | },
356 | {
357 | "cell_type": "code",
358 | "execution_count": 0,
359 | "metadata": {
360 | "colab": {
361 | "base_uri": "https://localhost:8080/",
362 | "height": 34
363 | },
364 | "colab_type": "code",
365 | "id": "Uq41czmlc51O",
366 | "outputId": "7a29da69-ff2f-4438-f20f-b71f7ba2b42f"
367 | },
368 | "outputs": [
369 | {
370 | "name": "stdout",
371 | "output_type": "stream",
372 | "text": [
373 | "Exception occured!\n"
374 | ]
375 | }
376 | ],
377 | "source": [
378 | "divide_numbers('abc',0)"
379 | ]
380 | },
381 | {
382 | "cell_type": "markdown",
383 | "metadata": {
384 | "colab_type": "text",
385 | "id": "y3UfZiYpc8xR"
386 | },
387 | "source": [
388 | "### **Raising exception**"
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 0,
394 | "metadata": {
395 | "colab": {},
396 | "colab_type": "code",
397 | "id": "IKPJB2tIc-d_"
398 | },
399 | "outputs": [],
400 | "source": [
401 | "def get_grade(score):\n",
402 | " if score>70:\n",
403 | " return \"A\"\n",
404 | " if score>=50 and score<=70:\n",
405 | " return \"B\"\n",
406 | " if score<50:\n",
407 | " return \"C\""
408 | ]
409 | },
410 | {
411 | "cell_type": "code",
412 | "execution_count": 0,
413 | "metadata": {
414 | "colab": {
415 | "base_uri": "https://localhost:8080/",
416 | "height": 34
417 | },
418 | "colab_type": "code",
419 | "id": "SQP_y6c8dATn",
420 | "outputId": "8e0a0d56-ddbb-498e-ece6-3e75d789c9d2"
421 | },
422 | "outputs": [
423 | {
424 | "data": {
425 | "text/plain": [
426 | "'A'"
427 | ]
428 | },
429 | "execution_count": 15,
430 | "metadata": {
431 | "tags": []
432 | },
433 | "output_type": "execute_result"
434 | }
435 | ],
436 | "source": [
437 | "get_grade(90)"
438 | ]
439 | },
440 | {
441 | "cell_type": "code",
442 | "execution_count": 0,
443 | "metadata": {
444 | "colab": {
445 | "base_uri": "https://localhost:8080/",
446 | "height": 34
447 | },
448 | "colab_type": "code",
449 | "id": "7-0DN04gdBqm",
450 | "outputId": "5d54497a-09ed-4d74-e3f9-40d41e32d29b"
451 | },
452 | "outputs": [
453 | {
454 | "data": {
455 | "text/plain": [
456 | "'C'"
457 | ]
458 | },
459 | "execution_count": 16,
460 | "metadata": {
461 | "tags": []
462 | },
463 | "output_type": "execute_result"
464 | }
465 | ],
466 | "source": [
467 | "get_grade(23)"
468 | ]
469 | },
470 | {
471 | "cell_type": "code",
472 | "execution_count": 0,
473 | "metadata": {
474 | "colab": {
475 | "base_uri": "https://localhost:8080/",
476 | "height": 34
477 | },
478 | "colab_type": "code",
479 | "id": "vupyGdL1dDfn",
480 | "outputId": "0a1986c0-b063-4612-c546-c53ee6dfaa24"
481 | },
482 | "outputs": [
483 | {
484 | "data": {
485 | "text/plain": [
486 | "'A'"
487 | ]
488 | },
489 | "execution_count": 17,
490 | "metadata": {
491 | "tags": []
492 | },
493 | "output_type": "execute_result"
494 | }
495 | ],
496 | "source": [
497 | "get_grade(200)"
498 | ]
499 | },
500 | {
501 | "cell_type": "markdown",
502 | "metadata": {
503 | "colab_type": "text",
504 | "id": "aHBCYAGZdEZx"
505 | },
506 | "source": [
507 | "**Here the max test score is 100. So passing 200 as a parameter to this function is clearly invalid. The function should be doing the validation that score should be between 0 to 100 and raising exception if it is out side this range.**"
508 | ]
509 | },
510 | {
511 | "cell_type": "code",
512 | "execution_count": 0,
513 | "metadata": {
514 | "colab": {},
515 | "colab_type": "code",
516 | "id": "nRcuv2mTdGPh"
517 | },
518 | "outputs": [],
519 | "source": [
520 | "def get_grade(score):\n",
521 | " if score<0 or score>100:\n",
522 | " raise ValueError(\"Invalid score\")\n",
523 | "\n",
524 | " if score>70:\n",
525 | " return \"A\"\n",
526 | " if score>=50 and score<=70:\n",
527 | " return \"B\"\n",
528 | " if score<50:\n",
529 | " return \"C\""
530 | ]
531 | },
532 | {
533 | "cell_type": "code",
534 | "execution_count": 0,
535 | "metadata": {
536 | "colab": {
537 | "base_uri": "https://localhost:8080/",
538 | "height": 284
539 | },
540 | "colab_type": "code",
541 | "id": "3XVL5NAydINa",
542 | "outputId": "06beddb3-488c-4ccb-aacd-b75be902c322"
543 | },
544 | "outputs": [
545 | {
546 | "ename": "ValueError",
547 | "evalue": "ignored",
548 | "output_type": "error",
549 | "traceback": [
550 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
551 | "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
552 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mget_grade\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m200\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
553 | "\u001b[0;32m\u001b[0m in \u001b[0;36mget_grade\u001b[0;34m(score)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mget_grade\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mscore\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mscore\u001b[0m\u001b[0;34m<\u001b[0m\u001b[0;36m0\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mscore\u001b[0m\u001b[0;34m>\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Invalid score\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mscore\u001b[0m\u001b[0;34m>\u001b[0m\u001b[0;36m70\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
554 | "\u001b[0;31mValueError\u001b[0m: Invalid score"
555 | ]
556 | }
557 | ],
558 | "source": [
559 | "get_grade(200)"
560 | ]
561 | },
562 | {
563 | "cell_type": "code",
564 | "execution_count": 0,
565 | "metadata": {
566 | "colab": {},
567 | "colab_type": "code",
568 | "id": "5C6ZjqordKse"
569 | },
570 | "outputs": [],
571 | "source": []
572 | },
573 | {
574 | "cell_type": "markdown",
575 | "metadata": {
576 | "colab_type": "text",
577 | "id": "nHDUEgzgdMR2"
578 | },
579 | "source": [
580 | "## **Excercise**"
581 | ]
582 | },
583 | {
584 | "cell_type": "markdown",
585 | "metadata": {
586 | "colab_type": "text",
587 | "id": "Xwgoad5xdNAv"
588 | },
589 | "source": [
590 | "**1. Write a function that takes file name as an input and returns the content of that file as an output. You will call this function for a file called idontexist.txt. This file doesn't exist, see what happens when you try to open this file. Now in your function handle file note opening exception and return a message to user saying that this file doesn't exist!**"
591 | ]
592 | },
593 | {
594 | "cell_type": "markdown",
595 | "metadata": {
596 | "colab_type": "text",
597 | "id": "KU3Y60iFdOv4"
598 | },
599 | "source": [
600 | "\n",
601 | "```\n",
602 | "def get_file_content(file_name):\n",
603 | " # your code goes here\n",
604 | "\n",
605 | "get_file_content(\"idontexist.txt\")\n",
606 | "```\n"
607 | ]
608 | },
609 | {
610 | "cell_type": "markdown",
611 | "metadata": {
612 | "colab_type": "text",
613 | "id": "-wgcd9fddQ15"
614 | },
615 | "source": [
616 | "**2. Write a function to calculate area of a triangle. This function takes base and height as parameters and computes triangle area by using formula,**\n",
617 | "\n",
618 | "```\n",
619 | "area = (base*height)/2\n",
620 | "```\n",
621 | "**Call this function using string arguments. See what happens. Now change your function such that it throws appropriate exception when data type of base and height is not a number. It should also throw exception when either base or height is negative**"
622 | ]
623 | },
624 | {
625 | "cell_type": "markdown",
626 | "metadata": {
627 | "colab_type": "text",
628 | "id": "RGtRqReOdSjO"
629 | },
630 | "source": [
631 | "\n",
632 | "\n",
633 | "```\n",
634 | "def triangle_area(base,height):\n",
635 | " # your code goes here\n",
636 | "\n",
637 | "triangle_area(20,10) # This works ok\n",
638 | "triangle_area(\"abc\",10) # This should throw exception saying base value is invalid\n",
639 | "triangle_area(23,\"\") # This should throw exception saying value of height is invalid\n",
640 | "triangle_area(-5,10) # This should throw exception saying base value can't be negative\n",
641 | "triangle_area(8,-3) # Throws exception saying height can't be negative\n",
642 | "```"
643 | ]
644 | }
645 | ],
646 | "metadata": {
647 | "colab": {
648 | "name": "exception_handling.ipynb",
649 | "provenance": []
650 | },
651 | "kernelspec": {
652 | "display_name": "Python 3",
653 | "language": "python",
654 | "name": "python3"
655 | },
656 | "language_info": {
657 | "codemirror_mode": {
658 | "name": "ipython",
659 | "version": 3
660 | },
661 | "file_extension": ".py",
662 | "mimetype": "text/x-python",
663 | "name": "python",
664 | "nbconvert_exporter": "python",
665 | "pygments_lexer": "ipython3",
666 | "version": "3.7.3"
667 | }
668 | },
669 | "nbformat": 4,
670 | "nbformat_minor": 1
671 | }
672 |
--------------------------------------------------------------------------------
/ObjectOrientedPython.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "LJ3LpvSozpAc"
8 | },
9 | "source": [
10 | "# What is object oriented programming?\n",
11 | "\n",
12 | "Structuring programs to reflect real world notions of objects and properties and how some objects have both similarities and differences in behavior.\n",
13 | "\n",
14 | "## Classes\n",
15 | "\n",
16 | "Let us look at some built in classes and objects thus created to understand how they share behavior yet have different data."
17 | ]
18 | },
19 | {
20 | "cell_type": "code",
21 | "execution_count": null,
22 | "metadata": {
23 | "colab": {},
24 | "colab_type": "code",
25 | "id": "J3hyXIUcznVt"
26 | },
27 | "outputs": [],
28 | "source": [
29 | "student = {\"name\": \"Alex\", \"age\": 19, \"major\": \"Mathematics\", \"degree\": \"BachelorOfSciece\", \"gpa\": 3.8}\n",
30 | "pet = {\"name\": \"Scooby\", \"type\": \"Labrador\", \"age\": 2, \"color\": \"black\"}\n",
31 | "rainbow_colors= (\"voilet\", \"indigo\", \"blue\", \"green\", \"yellow\", \"orange\", \"red\")\n",
32 | "model_name = \"Toyota Prius\"\n",
33 | "model_colors = [\"magenta\", \"cyan\"]\n",
34 | "model_year = 2020"
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": null,
40 | "metadata": {
41 | "colab": {},
42 | "colab_type": "code",
43 | "id": "qv48ZGhr23lG"
44 | },
45 | "outputs": [],
46 | "source": [
47 | "def get_attributes(obj):\n",
48 | " return [attr for attr in dir(obj) if not attr.startswith(\"_\")]\n"
49 | ]
50 | },
51 | {
52 | "cell_type": "code",
53 | "execution_count": null,
54 | "metadata": {
55 | "colab": {},
56 | "colab_type": "code",
57 | "id": "PLm_Bdq6_xDw"
58 | },
59 | "outputs": [],
60 | "source": [
61 | "for var in (student, pet, rainbow_colors, model_name, model_colors, model_year):\n",
62 | " print(type(var), get_attributes(var))\n",
63 | " input()"
64 | ]
65 | },
66 | {
67 | "cell_type": "code",
68 | "execution_count": null,
69 | "metadata": {
70 | "colab": {},
71 | "colab_type": "code",
72 | "id": "6NO-Wbcy6U-t"
73 | },
74 | "outputs": [],
75 | "source": [
76 | "for color in rainbow_colors: # can iterate over lists, tuples and strings\n",
77 | " print(color)\n",
78 | "\n",
79 | "for color in model_colors:\n",
80 | " print(color)\n",
81 | " \n",
82 | "for char in model_name:\n",
83 | " print(char)\n",
84 | "\n",
85 | "print(rainbow_colors[0:3]) # can also slice through lists, tuples and strings\n",
86 | "print(model_colors[0:3])\n",
87 | "print(model_name[0:3])\n"
88 | ]
89 | },
90 | {
91 | "cell_type": "code",
92 | "execution_count": null,
93 | "metadata": {},
94 | "outputs": [],
95 | "source": [
96 | "for digit in model_year:\n",
97 | " print(digit)"
98 | ]
99 | },
100 | {
101 | "cell_type": "code",
102 | "execution_count": null,
103 | "metadata": {},
104 | "outputs": [],
105 | "source": [
106 | "model_year[0:3]"
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": null,
112 | "metadata": {
113 | "colab": {},
114 | "colab_type": "code",
115 | "id": "3xQmmxtB9txE"
116 | },
117 | "outputs": [],
118 | "source": [
119 | "students.sort()\n",
120 | "print(student)\n",
121 | "\n",
122 | "rainbow_colors.sort() # tuples and lift are different when it comes to mutability"
123 | ]
124 | },
125 | {
126 | "cell_type": "code",
127 | "execution_count": null,
128 | "metadata": {
129 | "colab": {},
130 | "colab_type": "code",
131 | "id": "JL7bG8uNB9Mc"
132 | },
133 | "outputs": [],
134 | "source": [
135 | "print(student.items())\n",
136 | "student.sort() # dictionaries have different behavior"
137 | ]
138 | },
139 | {
140 | "cell_type": "markdown",
141 | "metadata": {
142 | "colab_type": "text",
143 | "id": "ZnNqn8GEBheJ"
144 | },
145 | "source": [
146 | "### Objects belonging to the same class have common attributes / behavior. \n",
147 | "\n",
148 | "These attributes can be either functions (also called methods) or data (variables).\n",
149 | "\n",
150 | "These common attributes give all objects of a class common behavior.\n",
151 | "\n",
152 | "For example, all lists can be sorted, reversed, you can calculate their length and do comprehensions on them."
153 | ]
154 | },
155 | {
156 | "cell_type": "markdown",
157 | "metadata": {
158 | "colab_type": "text",
159 | "id": "5qNQOtl8vipq"
160 | },
161 | "source": [
162 | "### Let's define a basic person class. The simplest class definition can look like:"
163 | ]
164 | },
165 | {
166 | "cell_type": "code",
167 | "execution_count": null,
168 | "metadata": {
169 | "colab": {},
170 | "colab_type": "code",
171 | "id": "epIQv3ZBBXot"
172 | },
173 | "outputs": [],
174 | "source": [
175 | "class Person:\n",
176 | " pass"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {
182 | "colab_type": "text",
183 | "id": "fWDjmhiGwTTB"
184 | },
185 | "source": [
186 | "Now, we can create objects of the person class."
187 | ]
188 | },
189 | {
190 | "cell_type": "code",
191 | "execution_count": null,
192 | "metadata": {
193 | "colab": {},
194 | "colab_type": "code",
195 | "id": "7E_SPrX7GlEJ"
196 | },
197 | "outputs": [],
198 | "source": [
199 | "p1 = Person()\n",
200 | "p2 = Person()"
201 | ]
202 | },
203 | {
204 | "cell_type": "code",
205 | "execution_count": null,
206 | "metadata": {
207 | "colab": {},
208 | "colab_type": "code",
209 | "id": "VcDNIQo_HKUS"
210 | },
211 | "outputs": [],
212 | "source": [
213 | "type(p1)"
214 | ]
215 | },
216 | {
217 | "cell_type": "code",
218 | "execution_count": null,
219 | "metadata": {
220 | "colab": {},
221 | "colab_type": "code",
222 | "id": "AWC2i4hywt8i"
223 | },
224 | "outputs": [],
225 | "source": [
226 | "isinstance(p2, Person)"
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "execution_count": null,
232 | "metadata": {
233 | "colab": {},
234 | "colab_type": "code",
235 | "id": "NVFK2jxKwx-5"
236 | },
237 | "outputs": [],
238 | "source": [
239 | "p1 == p2"
240 | ]
241 | },
242 | {
243 | "cell_type": "markdown",
244 | "metadata": {
245 | "colab_type": "text",
246 | "id": "k9lP_gmhxkVm"
247 | },
248 | "source": [
249 | "## Class objects support two kinds of operations: attribute references and instantiation. \n",
250 | "https://docs.python.org/3/tutorial/classes.html\n",
251 | "\n",
252 | "Let's look at examples of both"
253 | ]
254 | },
255 | {
256 | "cell_type": "code",
257 | "execution_count": null,
258 | "metadata": {
259 | "colab": {},
260 | "colab_type": "code",
261 | "id": "ERaasbfbxhiq"
262 | },
263 | "outputs": [],
264 | "source": [
265 | "class Person:\n",
266 | " species = \"Homo Sapeins\" # property shared across all objects\n",
267 | "\n",
268 | " def greet(self):\n",
269 | " # self is a reference to the instance calling this method\n",
270 | " return f\"Hello friend!\"\n",
271 | "\n",
272 | "p1 = Person()\n",
273 | "p2 = Person()\n",
274 | "print(p1.species)\n",
275 | "print(p2.greet())"
276 | ]
277 | },
278 | {
279 | "cell_type": "code",
280 | "execution_count": null,
281 | "metadata": {
282 | "colab": {},
283 | "colab_type": "code",
284 | "id": "81WGtXLw0enS"
285 | },
286 | "outputs": [],
287 | "source": [
288 | "print(p1 == p2)\n",
289 | "print(p1.species == p2.species)"
290 | ]
291 | },
292 | {
293 | "cell_type": "markdown",
294 | "metadata": {
295 | "colab_type": "text",
296 | "id": "hARyQq_LxjXm"
297 | },
298 | "source": [
299 | "### Instantiation operation\n",
300 | "\n",
301 | "In the Person class above, when you call Person(), python gives you an empty object. Each time you call `Person()`, a new object is returned. When you call `.greet()` on one such object, Python passes a reference of the object itself in `self`. \n",
302 | "\n",
303 | "If you want to construct an object with some state / parameters, you can define the `__init__` method\n"
304 | ]
305 | },
306 | {
307 | "cell_type": "code",
308 | "execution_count": null,
309 | "metadata": {
310 | "colab": {},
311 | "colab_type": "code",
312 | "id": "-KIqZfNiCvzF"
313 | },
314 | "outputs": [],
315 | "source": [
316 | "class Person:\n",
317 | " species = \"Homo Sapeins\" # property shared across all objects\n",
318 | " \n",
319 | " def __init__(self, name):\n",
320 | " self.name = name # store given name in the instance\n",
321 | "\n",
322 | " def greet(self, person):\n",
323 | " # self is a reference to the instance calling this method\n",
324 | " return \"Hello \" + person.name + \"! My name is \" + self.name # use instance specific data"
325 | ]
326 | },
327 | {
328 | "cell_type": "code",
329 | "execution_count": null,
330 | "metadata": {
331 | "colab": {},
332 | "colab_type": "code",
333 | "id": "aRH2BUPJC1Gh"
334 | },
335 | "outputs": [],
336 | "source": [
337 | "p1 = Person(\"Tom\")\n",
338 | "p2 = Person(\"Jerry\")\n",
339 | "p1.greet(p2)"
340 | ]
341 | },
342 | {
343 | "cell_type": "markdown",
344 | "metadata": {
345 | "colab_type": "text",
346 | "id": "KQWpy_E8AH8Z"
347 | },
348 | "source": [
349 | "#### Instance attributes\n",
350 | "\n",
351 | "Having attributes and functions that the class instances share is useful, but allowing each instance to store its own data is the more common use case. This way, class instances have similar behavior but conceptually represent a unique real-world entity.\n",
352 | "\n",
353 | "The `__init__` method is what python calls during object creation. You can pass arguments to this method that can be used or stored in the isntance itself.\n",
354 | "\n",
355 | "You can modify an objects attributes after instantiation as well. General convention is that an attribute with an _ prefix is intended to not be modified by a caller outside."
356 | ]
357 | },
358 | {
359 | "cell_type": "code",
360 | "execution_count": null,
361 | "metadata": {
362 | "colab": {},
363 | "colab_type": "code",
364 | "id": "cmUsIWCzAd0m"
365 | },
366 | "outputs": [],
367 | "source": [
368 | "from datetime import datetime, date\n",
369 | "\n",
370 | "class Person:\n",
371 | " species = \"Homo Sapeins\" # property shared across all objects\n",
372 | " \n",
373 | " def __init__(self, name, dob, ssn=None):\n",
374 | " self.name = name\n",
375 | " self._dob = dob\n",
376 | " self._ssn = ssn\n",
377 | "\n",
378 | " def greet(self, person):\n",
379 | " # self is a reference to the instance calling this method\n",
380 | " return \"Hello \" + person.name + \"! My name is \" + self.name \n",
381 | "\n",
382 | " def age(self):\n",
383 | " return datetime.now().date().year - self._dob.year"
384 | ]
385 | },
386 | {
387 | "cell_type": "code",
388 | "execution_count": null,
389 | "metadata": {
390 | "colab": {},
391 | "colab_type": "code",
392 | "id": "vsIzS5BPAm_v"
393 | },
394 | "outputs": [],
395 | "source": [
396 | "p1 = Person(\"Shashank\", date(2000, 1, 1), \"abc-def-ghij\") # passing arguments to instance construction\n",
397 | "print(p1.greet(p2))\n",
398 | "print(p1.age()) # method called on instance that can use its associated data attributes\n",
399 | "p1.name = \"Shashank Singh\"\n",
400 | "p1.greet(p2)\n",
401 | "\n",
402 | "p1._ssn = \"111-11-1111\" # not advisable unless you know what you are doing..."
403 | ]
404 | },
405 | {
406 | "cell_type": "markdown",
407 | "metadata": {
408 | "colab_type": "text",
409 | "id": "j3AFX7oDYbfG"
410 | },
411 | "source": [
412 | "## Excercise\n",
413 | "\n",
414 | "Create a function that finds the youngest and the oldest person from a list of people and the makes the oldest greet the youngest.\n",
415 | "\n",
416 | "\n",
417 | "\n",
418 | "\n"
419 | ]
420 | },
421 | {
422 | "cell_type": "code",
423 | "execution_count": null,
424 | "metadata": {
425 | "colab": {},
426 | "colab_type": "code",
427 | "id": "nE-IQC4vYa2T"
428 | },
429 | "outputs": [],
430 | "source": [
431 | "def old_greets_new(people):\n",
432 | " oldest = youngest = people[0]\n",
433 | " for person in people:\n",
434 | " if person.age() < youngest.age():\n",
435 | " youngest = person\n",
436 | " elif person.age() > oldest.age():\n",
437 | " oldest = person \n",
438 | " return oldest.greet(youngest)\n",
439 | "\n",
440 | "legends = [Person(\"Maradona\", date(1960, 10, 30)), Person(\"Zidane\", date(1972, 6, 23)), Person(\"Messi\", date(1987, 6, 24))]\n",
441 | "print(old_greets_new(legends))"
442 | ]
443 | },
444 | {
445 | "cell_type": "markdown",
446 | "metadata": {
447 | "colab_type": "text",
448 | "id": "edtnEM5CG3dW"
449 | },
450 | "source": [
451 | "# Inheritance\n",
452 | "\n",
453 | "\n",
454 | "Inheritance allows objects of derived classes to 'inherit' attributes from the base class and modify some inherited behavior if needed.\n",
455 | "\n",
456 | "\n",
457 | "For example, a base class `Triangle` could have a method called `area` that returns `1/2 * base * height`. We could have a derived class called `EquilateralTriangle` that only needs one dimension to be specified and it can determine the area with a different formula...\n",
458 | "\n"
459 | ]
460 | },
461 | {
462 | "cell_type": "code",
463 | "execution_count": null,
464 | "metadata": {},
465 | "outputs": [],
466 | "source": [
467 | "import math\n",
468 | "\n",
469 | "class Triangle:\n",
470 | " def __init__(self, base, height):\n",
471 | " self.base = base\n",
472 | " self.height = height\n",
473 | " \n",
474 | " def area(self):\n",
475 | " return 0.5 * self.base * self.height\n",
476 | "\n",
477 | " \n",
478 | "class EquilateralTriangle(Triangle):\n",
479 | " def __init__(self, side):\n",
480 | " height = math.sin(math.radians(60)) * side\n",
481 | " super().__init__(base=side, height=height) # calculate height and call parent constructor\n"
482 | ]
483 | },
484 | {
485 | "cell_type": "code",
486 | "execution_count": null,
487 | "metadata": {},
488 | "outputs": [],
489 | "source": [
490 | "triangle = Triangle(10, 10) # needs both base and height explicitly\n",
491 | "print(triangle.area())\n",
492 | "eq_triangle = EquilateralTriangle(10)\n",
493 | "print(eq_triangle.area()) # note that it did not have to implement its own area, it 'inherited' it "
494 | ]
495 | },
496 | {
497 | "cell_type": "markdown",
498 | "metadata": {},
499 | "source": [
500 | "In our Person example, we can create sub-classes called Student and Professor, who are both people."
501 | ]
502 | },
503 | {
504 | "cell_type": "code",
505 | "execution_count": null,
506 | "metadata": {
507 | "colab": {},
508 | "colab_type": "code",
509 | "id": "s5WGFNOfIMvq"
510 | },
511 | "outputs": [],
512 | "source": [
513 | "class Person:\n",
514 | " def __init__(self, name):\n",
515 | " self.name = name\n",
516 | "\n",
517 | " def greet(self, person):\n",
518 | " return \"Hello \" + person.name + \"! My name is \" + self.name \n",
519 | "\n",
520 | "\n",
521 | "class Student(Person): # A student inherits properties from person\n",
522 | "\n",
523 | " def __init__(self, name):\n",
524 | " super().__init__(name) # call the parent class constructor\n",
525 | " self.score = 0\n",
526 | " self.assignments = []\n",
527 | "\n",
528 | " def do_assignment(self, assignment):\n",
529 | " self.assignments.append(\"solved: \" + assignment)\n",
530 | "\n",
531 | "\n",
532 | "class Professor(Person): # A professor is also a person, inheriting person like behavior and properties\n",
533 | "\n",
534 | " def __init__(self, name, dept):\n",
535 | " super().__init__(name) # call the parent class constructor\n",
536 | " self.dept = dept\n",
537 | "\n",
538 | " def grade_assignments(self, student):\n",
539 | " for assignment in student.assignments:\n",
540 | " student.score += 1\n",
541 | " \n",
542 | " def greet(self, person): # this 'overrides' the greeting method provided by the parent\n",
543 | " return \"Hello \" + person.name + \"! I am Dr. \" + self.name \n"
544 | ]
545 | },
546 | {
547 | "cell_type": "code",
548 | "execution_count": null,
549 | "metadata": {
550 | "colab": {},
551 | "colab_type": "code",
552 | "id": "NKdblbEdIP4A"
553 | },
554 | "outputs": [],
555 | "source": [
556 | "sam = Student(\"Sam\")\n",
557 | "sam.do_assignment(\"Lesson1\")\n",
558 | "brooks = Professor(\"Brooks\", \"computer-science\")\n",
559 | "brooks.grade_assignments(sam)\n",
560 | "sam.score\n"
561 | ]
562 | },
563 | {
564 | "cell_type": "code",
565 | "execution_count": null,
566 | "metadata": {
567 | "colab": {},
568 | "colab_type": "code",
569 | "id": "O0kd1pJHRrGP"
570 | },
571 | "outputs": [],
572 | "source": [
573 | "isinstance(sam, Person)"
574 | ]
575 | },
576 | {
577 | "cell_type": "code",
578 | "execution_count": null,
579 | "metadata": {
580 | "colab": {},
581 | "colab_type": "code",
582 | "id": "8QzjMiusSf_4"
583 | },
584 | "outputs": [],
585 | "source": [
586 | "isinstance(brooks, Person)"
587 | ]
588 | },
589 | {
590 | "cell_type": "code",
591 | "execution_count": null,
592 | "metadata": {
593 | "colab": {},
594 | "colab_type": "code",
595 | "id": "Jaonoas0SjiY"
596 | },
597 | "outputs": [],
598 | "source": [
599 | "isinstance(brooks, Student)"
600 | ]
601 | },
602 | {
603 | "cell_type": "code",
604 | "execution_count": null,
605 | "metadata": {},
606 | "outputs": [],
607 | "source": [
608 | "sam.greet(brooks)"
609 | ]
610 | },
611 | {
612 | "cell_type": "code",
613 | "execution_count": null,
614 | "metadata": {},
615 | "outputs": [],
616 | "source": [
617 | "brooks.greet(sam)"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {},
623 | "source": [
624 | "### Exercise\n",
625 | "\n",
626 | "1. Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle.\n",
627 | "\n",
628 | "2. Use `dir` on an instance of a circle thus created. Change the radius attribute and calculate the area again.\n",
629 | "\n",
630 | "3. Rewrite your stock exercise with classes with the added functionality that the file now contains another column called person. Each person can own multiple stocks of multiple companies. Write a method in the Person class that gives the total stocks and their value of a particular company. Write another method that gives the total portfolio value."
631 | ]
632 | }
633 | ],
634 | "metadata": {
635 | "colab": {
636 | "name": "ObjectOrientedPython.ipynb",
637 | "provenance": []
638 | },
639 | "kernelspec": {
640 | "display_name": "Python 3",
641 | "language": "python",
642 | "name": "python3"
643 | },
644 | "language_info": {
645 | "codemirror_mode": {
646 | "name": "ipython",
647 | "version": 3
648 | },
649 | "file_extension": ".py",
650 | "mimetype": "text/x-python",
651 | "name": "python",
652 | "nbconvert_exporter": "python",
653 | "pygments_lexer": "ipython3",
654 | "version": "3.6.9"
655 | }
656 | },
657 | "nbformat": 4,
658 | "nbformat_minor": 1
659 | }
660 |
--------------------------------------------------------------------------------