Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Fundamentals - Basic | WeiYuan

WeiYuan
August 03, 2018

Python Fundamentals - Basic | WeiYuan

Python Fundamentals - Basic

WeiYuan

August 03, 2018
Tweet

More Decks by WeiYuan

Other Decks in Technology

Transcript

  1. § 全端工程師 + 資料科學家 ST2DE 計劃發起人,擅長網站開發與資料科學的雙棲 工程師,熟悉的語言是 Python 跟 JavaScript,喜歡

    用程式與技術的思維解決問題。 - 2018 總統盃黑客松 冠軍隊伍 - 2017 資料科學愛好者年會(DSCONF) 講師 - 2017 行動科技年會(MOPCON) 講師 - 2016 微軟 Imagine Cup 台灣區冠軍 site: v123582.tw / line: weiwei63 mail: [email protected]
  2. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 3
  3. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 4
  4. Introduction § The Zen of Python: Beautiful, Explicit, Simple link

    § High-level and Interpreted programming language § OOP + FP multi-paradigm § Python 2.x or Python 3.x ? § Environment: `python --version` § Runtime: shell, command, jupyter/ipython, anaconda § Editor/IDE: sublime text, pycharm, spider(built in anaconda) § PIP: packages manager of python <- default § Pyenv, Vitrualenv <- need to install 5
  5. 8

  6. Python 2.x or Python 3.x ? 11 1. Python 團隊將於

    2020 年 1 月 1 日停止支持 Python 2.7 2. Python 正式正名代表為 Python3
  7. 12

  8. Python Ecosystem for Data Science § Request、beatifulsoup、Scrapy § NumPy、 SciPy、

    Pandas § Matplotlib、 Seaborn、 Bokeh、 Plotly § Statsmodels、SciKit-Learn、xgboost § TensorFlow(Theano)、Pytorch、Keras § NLTK、Gensim 14
  9. Python Ecosystem for Data Science § Request、beatifulsoup、Scrapy =>資料收集 § NumPy、

    SciPy、 Pandas => 資料前處理 § Matplotlib、 Seaborn、 Bokeh、 Plotly => 資料視覺化 § Statsmodels、SciKit-Learn、xgboost => 資料模型訓練 § TensorFlow(Theano)、Pytorch、Keras => 深度學習 § NLTK、Gensim => 自然語言與文本資料處理 15
  10. Runtime & Develop § 怎麼執行 Python 程式? shell / command

    / Jupyter notebook § 在哪裡寫 Python 程式碼? editor / IDE 16
  11. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 25
  12. Hello World Variable and Assign 26 1 2 3 4

    5 6 7 8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) Import Library Encoding Declaration Comment Indentation and Block Input and Output
  13. Hello World 27 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) Encoding Declaration Comment
  14. Hello World 28 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) Import Library § Library = module = package = a set of functions
  15. Hello World Variable and Assign 29 1 2 3 4

    5 6 7 8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) § Case Sensitivity § Weekly/Loosely Typed
  16. Hello World 30 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) Indentation and Block Spaces of Tab ?
  17. Hello World 31 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 15 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # ['False', 'None' . . .] import this, keyword from keyword import kwlist from keyword import * keywords = kwlist if len(keywords) > 0: print(keywords) x = input("Input Something...") print("%s" % (x)) Input and Output
  18. Outline § Introduction § HelloWorld § Data Types & Operator

    § Flow Control § Function § Class § Exception § File IO 32
  19. Primitive Types § Numeric type (int / float) § String

    type (str) § Boolean type (bool) 34
  20. Built-in Functions 35 1 2 3 4 5 6 type()

    dir() help() https://docs.python.org/3/library/functions.html
  21. Common Types & Operator 37 expression = operator (symbols)+ operand

    (variables) arithmetic comparison logical bitwise
  22. Numeric type (int / float) 38 1 2 3 4

    5 6 7 8 9 10 a = 20 a, b, c, d = 20, 5.5, True print(type(a)) # <class 'int'> print(type(b)) # <class 'float'> print(type(c)) # <class 'bool'> print(isinstance(a, int)) # True print(isinstance(b, int)) # False
  23. Numeric type (int / float) 39 1 2 3 4

    5 6 7 8 9 10 11 4 + 2 4.0 + 2 4.0 + 2.0 2 / 5 2.0 / 5 2 / 5.0 2.0 / 5.0 2 // 5 2 % 5
  24. Numeric type (int / float) 40 1 2 3 4

    5 6 7 8 9 10 11 # python2 w = 49 h = 163 bmi = 49 / (163/100)**2 print(bmi) # 49 # python3 w = 49.0 h = 163.0 bmi = 49 / (163/100)**2 print(bmi) # 18.4425...
  25. Try it! § #練習:Set the following variables to the corresponding

    values: 1. my_int to the value 7 2. my_float to the value 1.23 3. my_bool to the value True 41
  26. Try it! 42 1 2 3 4 5 6 7

    8 9 10 11 1 + 3*2 # 1 + 3**2 # (1 + 3)*2 # 1 + 3 / 2 *2 # 1 + 3 // 2 *2 # 1 + 3 / 2 **2 # 1 + 3 // 2 **2 # int(1 + 3 / 2 *2) # float(1 + 3 // 2 **2) # § #練習:Set the following variables to the corresponding
  27. Try it! 43 1 2 3 4 5 6 7

    8 9 10 11 a = input() b = input() ''' Your Code ''' print(‘The sum of ’, a, ‘and’ ,b , ‘is’, a+b) § #練習:Add two numbers
  28. Try it! 44 1 2 3 4 5 6 7

    8 9 10 11 a = input() b = input() ''' Your Code ''' print(‘The sum of ’, a, ‘and’ ,b , ‘is’, a+b) § #練習:承上題,要如何改成 a, b, c, d 四個輸⼊:
  29. Try it! 45 1 2 3 4 5 6 7

    8 9 10 11 num = 9 ''' Your Code ''' print('The square root of %0.3f is %0.3f' % (num ,num_sqrt)) § #練習:Find the Square Root
  30. Try it! 46 1 2 3 4 5 6 7

    8 9 10 11 a = 5 b = 10 ''' Your Code ''' print(a, b) # 10, 5 § #練習:Swap Two Variables
  31. String Type - Operations 47 1 2 3 4 5

    6 7 8 9 10 a = '12345' b = 'hello world' c = '\n' d = r'\n' e = '\\n' print(b + str(a) + c + d + e) print(b + str(a) + str(c) + str(d) + str(e))
  32. String Type - Index & Slice 48 1 2 3

    4 5 6 7 8 9 10 s = 'hello world' s[0], s[1], s[-1] s[0:5], s[0:len(t)], s[:] s[1:5:2], s[::-1]
  33. String Type - Methods 49 1 2 3 4 5

    6 7 8 9 10 b = 'hello world' dir(b)
  34. String Type 50 1 2 3 4 5 6 7

    8 9 10 split() find() replace() len() lower() upper() isdigit() isnumeric() isalpha()
  35. Try it! § #練習:Write a Python program to get a

    string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. • Sample Input: w3resource • Sample Output: w3ce 52
  36. Try it! § #練習:將字串當中的 not that poor 換成 good 。

    • Sample Input: The company is not that poor! • Sample Output: The company is good! 53
  37. Try it! § #練習:將字串當中的 not … poor 換成 good 。

    • Sample Input: The company is not that poor! • Sample Output: The company is good! 54
  38. #Note. Formatting String 56 1 2 3 4 5 6

    7 8 9 10 a, b, sum = 2, 3, 5 '%s + %s = %s ' % (a, b, sum) '{} + {} = {} '.format(a, b, sum) '{x} + {y} = {z} '.format(x=a, y=b, z=sum) f'The sum of {a} and {b} is {sum}'
  39. #Note. Formatting String 57 1 2 3 4 5 6

    7 8 9 10 a, b, sum = 2, 3, 5 '%s + %s = %s ' % (a, b, sum) '%d + %d = %d ' % (a, b, sum) '%f + %f = %f ' % (a, b, sum)
  40. #Note. Formatting String 58 1 2 3 4 5 6

    7 8 9 10 a, b, c = ‘x’, ‘y’, ‘z’ '%s, %s, %s ' % (a, b, c) '%d, %d, %d ' % (a, b, c) '%f, %f, %f ' % (a, b, c)
  41. #Note. Formatting String 59 1 2 3 4 5 6

    7 8 9 10 a, b, sum = 20.12, 30.123, 50.243 '%s + %s = %s ' % (a, b, sum) '%5d + %6d = %7d ' % (a, b, sum) '%5.1f + %6.2f = %8.3f ' % (a, b, sum)
  42. #Note. Formatting String 60 1 2 3 4 5 6

    7 8 9 10 %s => string %d => decimal %f => float \n => new line \t => tab
  43. Container Types 62 § list [,] => mutable sequence §

    tuple (,) => immutable sequence § dict {:,} => mutable collection of key-value mapped element § set {,} => mutable collections of unique elements
  44. Container Types 63 § list [,] => mutable sequence §

    tuple (,) => immutable sequence § dict {:,} => mutable collection of key-value mapped element § set {,} => mutable collections of unique elements
  45. Container Types 64 § list [,] => mutable sequence §

    tuple (,) => immutable sequence § dict {:,} => mutable collection of key-value mapped element § set {,} => mutable collections of unique elements
  46. Container Types 65 § list [,] => # l =

    [1, 2, 3, 4], l[0] = 999 § tuple (,) => # t = (1, 2), t[0] = 999 § dict {:,} => # d = {1: 100, 2: 200}, d[1] § set {,} => # s = {1, 2, 3}
  47. List - Operations 67 1 2 3 4 5 6

    7 8 9 10 L = [1, 2, 3, 4] G = [3, 4, 5, 6] L + G # [1, 2, 3, 4, 3, 4, 5, 6] L – G # 不存在 L * 2 # [1, 2, 3, 4, 1, 2, 3, 4] L / 2 # 不存在
  48. List – Index & Slice 68 1 2 3 4

    5 6 7 8 9 10 L = [1, 2, 3, 4, 5, 6] L[0], L[1], L[-1] L[0] = 999 L[0:5], L[0:len(L)], L[:] L[1:5:2], L[::-1]
  49. List - Methods 70 1 2 3 4 5 6

    7 8 9 10 my_list = [2] # [2] my_list.append(2) # [2, 2] my_list.extend([2]) # [2, 2, 2] my_list.insert(0, 3) # [3, 2, 2, 2] my_list.pop() # [3, 2, 2] my_list.remove(2) # [3, 2] my_list.sort() # [2, 3] my_list.reverse() # [3, 2]
  50. List - Operations 71 1 2 3 4 5 6

    7 8 9 10 my_list.count(2) # 1 len(my_list) # 2 sum(my_list) # 5 ‘2, 3’.split(‘, ’) # [2, 3] ', '.join([2, 3]) # '2, 3'
  51. Try it! § #練習:有一個列表,其中包括 10 個元素,例如這個列表是 [1, 2, 3, 4,

    5, 6, 7, 8, 9, 0],要求將最右邊的 0 移到最左邊,結果會 變成 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 72
  52. Try it! § #練習:有一個列表,其中包括 10 個元素,例如這個列表是 [1, 2, 3, 4,

    5, 6, 7, 8, 9, 0],要求將最左邊的 1 移到最右邊,結果會 變成 [2, 3, 4, 5, 6, 7, 8, 9, 0, 1] 73
  53. Try it! § #練習:Write a Python program to replace the

    last element in a list with another list. • Sample Input: num1 = [1, 3, 5, 7, 9, 10], num2 = [2, 4, 6, 8] • Sample Output: [1, 3, 5, 7, 9, 2, 4, 6, 8] 75
  54. Tuple 76 § Tuple – Operations § Tuple – Index

    & Slice § Tuple – Destructuring & Swaping
  55. Tuple - Operations 77 1 2 3 4 5 6

    7 8 9 10 t1 = (1, 2, 3) t1 = (4, 5, 6) t1 + t2 t1 * 2
  56. Tuple – Index & Slice 78 1 2 3 4

    5 6 7 8 9 10 t = (1, 2, 3, 4, 5, 6) t[0], t[1], t[-1] t[0] = 999 t[0:5], t[0:len(t)], t[:] t[1:5:2], t[::-1]
  57. Destructuring & Swaping 80 1 2 3 4 5 6

    7 8 9 10 (a, b) = my_list (a, b) = (b, a)
  58. Try it! § #練習:Swap Two Variables 81 1 2 3

    4 5 6 7 8 9 10 11 a = 5 b = 10 ''' Your Code ''' print(a, b) # 10, 5
  59. Dictionary – Operations 83 1 2 3 4 5 6

    7 8 9 10 my_dict = {'Mark': 1, 'test': 0} print(my_dict[’Mark’]) # 1 print(my_dict[0]) my_dict['Mary'] = 2 # {'Mark': 1, 'test': 0, ‘Mary’: 2} del my_dict['test']
  60. Dictionary – Unordered to Ordered 84 1 2 3 4

    5 6 7 8 9 10 my_dict.items() # dict_items([('Mark', 1), ('Mary', 2) ]) my_dict.keys() # dict_keys(['Mark', 'Mary']) my_dict.values() # dict_values([1, 2])
  61. Dictionary – Key Error 85 1 2 3 4 5

    6 7 8 9 10 my_dict['Tom'] # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # KeyError: ‘Tom’ my_dict.get('Tom', ''), my_dict # '', {'Mark': 1, 'test': 0} my_dict.setdefault('Tom', 3), my_dict # 3, {'Tom': 3, 'Mark': 1, 'test': 0}
  62. Try it! § #練習: Write a Python program to concatenate

    following dictionaries to create a new one 86 1 2 3 4 5 6 7 8 9 10 11 # Input: dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50, 6:60} ''' Your Code ''’ # Output: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
  63. Try it! § #練習:Write a Python program to check if

    a given key already exists in a dictionary. § 87 1 2 3 4 5 6 7 8 9 10 11 # Input: d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} key = input() ''' Your Code ''' # Output: Yes, the key is in this dict. or # No, the key is not in this dict.
  64. Set – Operations 89 1 2 3 4 5 6

    7 8 9 10 dmins = {'admin'} users = {'admin', 'user1', 'user2'} 'Justin' in admins # False admins & users # {'admin'} admins | users # {'admin', 'user1', 'user2'} admins - users # {} users – admins # {‘user1’, ‘user2’} admins ^ users # {user1, user2}
  65. Try it! § #練習: Illustrate Different Set Operations 90 1

    2 3 4 5 6 7 8 9 10 11 # define three sets E, N = {0, 2, 4, 6, 8}, {1, 2, 3, 4, 5} print("Intersection of E and N is", E & N) # 2, 4 print("Union of E and N is",E | N) # 0 1 2 3 4 5 6 8 print("Difference of E and N is",E - N) # 1 3 5 print("Symmetric difference of E and N is",E ^ N) # 0 1 3 5 6 8
  66. Try it! § #練習: Remove the repeated elements from the

    list, and sort it Decreasingly. 91 1 2 3 4 5 6 7 8 9 10 11 l = [1, 1, 3, 9, 7, 8, 8, 8] ''' Your Code ''' # Output: [9, 8, 7, 3, 1]
  67. Container Types 92 § list [,] => Operations / Index

    & Slice / Methods § tuple (,) => Operations / Index & Slice /Destructuring & Swaping § dict {:,} => Operations / Unordered to Ordered / Key Error § set {,} => Operations
  68. 93 § Mutable objects • list, dict, set § Immutable

    objects • int, float, complex, string, tuple Reference: https://www.linkedin.com/pulse/mutable-vs-immutable-objects-python-megha-mohan Im vs Mutable ?
  69. tuple vs list? § slower but more powerful than tuples.

    § Lists can be modified, and they have lots of handy operations we can perform on them. § Tuples are immutable and have fewer features. § To convert between tuples and lists use the list() and tuple() functions: • li = list(tu) • tu = tuple(li) 95
  70. iterator, iterable, iteration 97 1 2 3 4 5 6

    7 8 9 10 11 12 13 14 list = [1, 2, 3] iterator = iter(list) import sys sys.getsizeof(list) sys.getsizeof(iterator) for i in list: print(i) for i in iterator: print(i) print(next(iterator))
  71. iterator, iterable, iteration 98 1 2 3 4 5 6

    7 8 9 10 11 12 13 14 15 def f(): i = 1 return i def g(): i = 1 yield i i = 2 yield i a = f() b = g() print(a) print(next(b))
  72. bulit-in method 99 1 2 3 4 5 6 7

    8 dir(list) # ['append', 'clear', 'copy', 'count', 'extend', 'index',# 'insert', 'pop', 'remove', 'reverse', 'sort'] help(list.extend) # extend(...) # L.extend(iterable) -> None # extend list by appending elements from the iterable Reference: https://docs.python.org/3/library/functions.html
  73. Try it! § #練習:要求使⽤者輸⼊ n ,印出從 n 平⽅的對數值(Log) • hint:引入一個

    math 的函式庫,並且利用 dir 與 math 查看 log 函式怎 麼使用 100
  74. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 101
  75. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 102
  76. Common Types & Operator § Numeric type • int, float,

    bool, complex • expression => operator + operand § String type § Container type • list, tuple, dict, set 103 § expression = operator + operand (varibles) • arithmetic, comparison arithmetic comparison logical bitwise
  77. Flow Control § Logical Operator § Comparison Operator 104 1

    2 3 3 is 2, 3 is not 2 True and False, True or False 3 in [1, 2, 3, 4] 1 2 > 2, 2 >= 2, 2 == 2, 2 != 2
  78. Flow Control § Logical Operator => return Boolean § Comparison

    Operator => return Boolean 105 1 2 3 3 is 2, 3 is not 2 True and False, True or False 3 in [1, 2, 3, 4] 1 2 > 2, 2 >= 2, 2 == 2, 2 != 2
  79. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 108 1 2 3 4 5 6 7 8 9 if condition: ... elif condition: ... else: ... a = ... if condition else ...
  80. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 110 1 2 while condition: ....
  81. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 111 1 2 3 4 5 for i in [...]: ... a = [i for i in [...]] # list b = (i for i in [...]) # generator
  82. Try it! § #練習:有一個列表,其中包括 10 個元素,例如這個列表是 [1, 2, 3, 4,

    5, 6, 7, 8, 9, 0],要求將列表中的每個元素一次向前移動一 個位置,第一個元素到列表的最後,然後輸出這個列表。最終樣 式是 [2, 3, 4, 5, 6, 7, 8, 9, 0, 1],如果要把偶數放前⾯,奇數放 後⾯該怎麼做?結果像是 [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] 112
  83. Try it! § #練習:"Please count the character here." 115 1

    2 3 4 5 6 7 8 9 10 # {'r': 3, 'c': 3, 't': 3, ' ': 4, 'n': 1, 'u': 1, 'h': 3, 'e': 6, 'l': 1, 'o': 1, 'a': 3, 's': 1, 'P': 1, '.': 1}
  84. Try it! § #練習:"Here are UPPERCASE and lowercase chars." 116

    1 2 3 4 5 6 7 8 9 10 # {'c': ['c', 'c'], 'R': ['R'], 'w': ['w'], ' ': [' ', ' ', ' ', ' ', ' '], '.': ['.'], 'n': ['n'], 'H': ['H'], 'P': ['P', 'P'], 'h': ['h'], 'S': ['S'], 'e': ['e', 'e', 'e', 'e', 'e'], 'l': ['l'], 'E': ['E', 'E'], 'U': ['U'], 'a': ['a', 'a', 'a', 'a'], 'A': ['A'], 'o': ['o'], 'C': ['C'], 'r': ['r', 'r', 'r', 'r'], 'd': ['d'], 's': ['s', 's']}
  85. Try it! § #練習:畫各種三⾓形與變形 117 * ** *** **** *

    ** *** **** * *** ***** ******* * *** ***** ******* ********* ******* ***** *** *
  86. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 119
  87. Flow Control § if - elif - else § while

    § for in § break, continue § range(), zip(), enumerate() 120 1 2 3 4 5 6 7 8 for i in range(1, 3): print(i) for i, j in zip([a, b, c], [1, 2, 3]): print(i, j) for i,j in enumerate([a, b, c]): print(i, j)
  88. More zip() … 121 1 2 3 4 5 6

    7 8 9 10 result1 = [2, 4, 6, 8] result2 = [11, 13, 15, 17] for i, j in zip(result1, result2) print(i + j) # 2 11 # 4 13 # 6 15 # 8 17
  89. More zip() … 122 1 2 3 4 5 6

    7 8 9 10 11 12 13 result3 = [(2, 11), (4, 13), (6, 15), (8, 17)] for i in zip(*result3): print(i) # (2, 4, 6, 8) # (11, 13, 15, 17) for i in map(list,zip(*result3)): print(i) # [2, 4, 6, 8] # [11, 13, 15, 17]
  90. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 128
  91. Function 129 1 2 3 4 5 6 7 8

    9 max1 = a if a > b else b... max2 = x if x > y else y... a = 123 b = 234 // declare funcetion def max(a, b): return a if a > b else b // call function max(10, 20) maximum = max maximum(10, 20) # 20
  92. Basic Method for Call Function 130 1 2 3 4

    5 6 7 def f(x=100, y=200): return x, y f(1, 2) f(y=2, x=1) f(*(1, 2)) f(**{y=2, x=1})
  93. *args 134 1 2 3 4 5 6 7 8

    9 10 def foo(*args): print(args) foo(1,2,3) # (1, 2, 3) foo("qiwsir","qiwsir.github.io","python") # ('qiwsir', 'qiwsir.github.io', 'python') foo("qiwsir",307,["qiwsir",2],{"name":"qiwsir"}) # ('qiwsir', 307, ['qiwsir', 2], {'lang': 'python'})
  94. **kargs 135 1 2 3 4 5 def foo(**kargs): print(kargs)

    foo(a=1,b=2,c=3) # {'a': 1, 'c': 3, 'b': 2}
  95. type1 + type2 + type3 136 1 2 3 4

    5 6 7 8 9 10 11 12 13 14 15 def foo(x,y,z,*args,**kargs): print(x) print(y) print(z) print(args) print(kargs) foo('qiwsir',2,"python") # qiwsir# 2 # python# ()# {} foo(1,2,3,4,5) # 1# 2# 3# (4, 5)# {} foo(1,2,3,4,5,name="qiwsir") # 1# 2# 3# (4, 5)# {'name': 'qiwsir'}
  96. Try it! § #練習:以下程式會如何輸出? 138 1 2 3 4 5

    6 7 8 9 10 11 12 def foo(x,y=‘hello’,*targs,**dargs): print "x==>",x print "y==>",y print "targs_tuple==>",targs print "dargs_dict==>",dargs foo("1x") foo("1x","2y") foo("1x","2y","3t1","3t2") foo("1x","2y","3t1","3t2",d1="4d1",d2="4d2")
  97. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 141
  98. OOP Concept § Abstraction § Encapsulation => public, private §

    Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 149
  99. Class Objects 151 1 2 3 4 5 6 7

    8 class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world %s' % (self.i)
  100. Class Objects 152 1 2 3 4 5 6 7

    8 class MyClass: """A simple example class""" def __init__(self, i): self.i = i def f(self): return 'hello world %s' % (self.i)
  101. Class and Object 153 1 2 3 4 5 6

    7 8 class Animal: def __init__(self, name): self.name = name def call(): return ‘汪汪’ a = Animal('動物') print(a.name) print(a.call())
  102. 154 1 2 3 4 5 6 7 8 9

    10 class BankAccount: type = 'Normal Account' def __init__(self, name): self.userName = name self.balance = 0.0 def __str__(self): return self.name 11 12 13 14 15 16 17 18 19 20 21 22 def showBalance(self): print self.balance return def withdrawMoney(self, amount): self.balance -= amount self.check() return def depositMoney(self, amount): self.balance += amount return def check() Creating a Class
  103. 155 1 2 3 4 5 6 7 8 9

    10 object1 = BankAccount("Im 1") object1.userName object1.depositMoney(100) print object1.balance object1.showBalance() print object1.type Create an Object 1 2 3 4 5 6 7 8 9 10 object2 = BankAccount("Im 2") object2.userName object2.depositMoney(200) print object2.balance object2.showBalance() print object2.type
  104. 156 1 2 3 4 5 6 7 8 9

    10 account3 = BankAccount() print(account3.__class__) print(type(account3)) string = 'Cat' print(string.__class__) print(type(string)) Create an Object
  105. Try it! § #練習:利⽤上述建⽴的類別,宣告幾個物件,並放到⼀個 dict 保存。 § TomObj = student(‘Tom’,

    ‘male’, 22) § stduents = {‘Tom’: TomObj , ‘Mary’: obj} § stduents.Tom.age § stduents.Mary.age 158
  106. OOP Concept § Abstraction § Encapsulation => public, private §

    Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 159
  107. Inherit 160 1 2 3 4 5 6 7 8

    9 1 0 class Dog(Animal): def __init__(self, name, age): super().__init__(name) self.age = age # override def call(): print('汪汪汪') def call(ishungry): print(’T____T') d = Dog('小白', 13) print(d.name) 1 2 3 4 5 6 7 8 class Animal: def __init__(self, name): self.name = name def call(): return ‘汪汪’ a = Animal('動物') print(a.name) print(a.call())
  108. Inherit 161 1 2 3 4 5 6 7 8

    9 1 0 class Cat(Animal): def __init__(self, name, age): super().__init__(name) self.age = age # override def call(): print(’喵喵喵') d = Dog(‘小花', 13) print(d.name) 1 2 3 4 5 6 7 8 class Animal: def __init__(self, name): self.name = name def call(): return ‘汪汪’ a = Animal('動物') print(a.name) print(a.call())
  109. Inherit 162 1 2 3 4 5 6 7 8

    9 10 class ExecutiveAccount( BankAccount ): def requestCredit(self, amount): self.balance += amount executive = ExecutiveAccount()
  110. OOP Concept § Abstraction § Encapsulation => public, private §

    Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 163
  111. Private 164 1 2 3 4 5 6 7 8

    9 10 class Human: def __init__(self,h=0,w=0): self.height=h self.weight=w def BMI(self): return self.weight / ((self.height/100)**2) a = Human(180,80) print(a.height,a.weight) print(a.BMI())
  112. Private 165 1 2 3 4 5 6 7 8

    9 10 class Human: def __init__(self,h=0,w=0): self.__height=h self.__weight=w def __BMI(self): return self.__weight / ((self.__height/100)**2) a = Human(180,80) print(a.__height,a.__weight) print(a.__BMI())
  113. Private 166 1 2 3 4 5 6 7 8

    9 10 class Human: def __init__(self,h=0,w=0): self.__height=h self.__weight=w def __BMI(self): return self.__weight / ((self.__height/100)**2) def getBMI(self): return self.__BMI() a = myclass.Human(180,80) print(a.getBMI())
  114. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 167
  115. Error Exception 168 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 10 * (1/0) 4 + spam*3 '2' + 2
  116. Error Exception 169 1 2 3 4 5 6 7

    8 9 10 11 12 13 14 10 * (1/0) # Traceback (most recent call last): # File "<stdin>", line 1, in <module>ZeroDivisionError: division by zero 4 + spam*3 # Traceback (most recent call last): # File "<stdin>", line 1, in <module>NameError: name 'spam' is not defined '2' + 2 # Traceback (most recent call last): # File "<stdin>", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly
  117. try-except 170 1 2 3 4 5 6 7 8

    9 10 11 12 13 14 15 16 17 18 19 try: x = input("the first number:") y = input("the second number:") r = float(x)/float(y) print(r) except Exception as e: print(e) the first number: 2 the second number: 0 # float division by zero the first number: 2 the second number: a # could not convert string to float: a the first number: 4 the second number: 2 # 2.0
  118. Finally 171 1 2 3 4 5 6 7 8

    9 10 11 12 13 14 15 16 try: do something except: raise NameError('HiThere') do something finally do something try: file = open("test.py") except: print('Read file error') finally: file.close()
  119. Outline § Introduction § HelloWorld § Common Types & Operator

    § Flow Control § Function § Class § Exception § File IO 172
  120. File Write 173 1 2 3 fh = open("example.txt", "w")

    fh.write(”hello world") fh.close()
  121. With 175 1 2 3 4 5 with open("example.txt", "w")

    as fh: fh.write(”hello world") with open("example.txt", "r") as fh: fh.read()
  122. mode 176 r 以只读⽅式打开⽂件。⽂件的指针将会放在⽂件的开头。这是默认模式。 r+ 打开⼀个⽂件⽤于读写。⽂件指针将会放在⽂件的开头。 w 打开⼀个⽂件只⽤于写⼊。如果该⽂件已存在则将其覆盖。如果该⽂件不存 在,创建新⽂件。 w+

    打开⼀个⽂件⽤于读写。如果该⽂件已存在则将其覆盖。如果该⽂件不存在, 创建新⽂件。 a 打开⼀个⽂件⽤于追加。如果该⽂件已存在,⽂件指针将会放在⽂件的结尾。 也就是说,新的内容将会被写⼊到已有内容之后。如果该⽂件不存在,创建 新⽂件进⾏写⼊。 a+ 打开⼀个⽂件⽤于读写。如果该⽂件已存在,⽂件指针将会放在⽂件的结尾。 ⽂件打开时会是追加模式。如果该⽂件不存在,创建新⽂件⽤于读写。