Slide 1

Slide 1 text

Python Fundamentals - Basic 給新⼿的 Python 程式設計 | WeiYuan

Slide 2

Slide 2 text

§ 全端工程師 + 資料科學家 ST2DE 計劃發起人,擅長網站開發與資料科學的雙棲 工程師,熟悉的語言是 Python 跟 JavaScript,喜歡 用程式與技術的思維解決問題。 - 2018 總統盃黑客松 冠軍隊伍 - 2017 資料科學愛好者年會(DSCONF) 講師 - 2017 行動科技年會(MOPCON) 講師 - 2016 微軟 Imagine Cup 台灣區冠軍 site: v123582.tw / line: weiwei63 mail: [email protected]

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

6 Explicit 清楚 Beautiful 漂亮 Simple 簡單

Slide 7

Slide 7 text

7 Explicit 清楚 Beautiful 漂亮 Simple 簡單

Slide 8

Slide 8 text

8

Slide 9

Slide 9 text

Python 2.x or Python 3.x ? 9

Slide 10

Slide 10 text

Python 2.x or Python 3.x ? 10

Slide 11

Slide 11 text

Python 2.x or Python 3.x ? 11 1. Python 團隊將於 2020 年 1 月 1 日停止支持 Python 2.7 2. Python 正式正名代表為 Python3

Slide 12

Slide 12 text

12

Slide 13

Slide 13 text

13 選擇 Python 做為程式語言的兩個原因: ① 程式語法簡單好寫 ② 第三方資源豐富

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

Runtime & Develop § 怎麼執行 Python 程式? shell / command / Jupyter notebook § 在哪裡寫 Python 程式碼? editor / IDE 16

Slide 17

Slide 17 text

Python 環境、套件安裝與使用 一個開發環境包含「程式語言執行環境」、「開發/編輯環境」、 「第三方套件」。可能會存在版本或是專案上的差異,因此常見的 管理工具有以下: § Anaconda 集成式開發軟體 § PIP 套件管理工具 § Pyenv 多版本Python管理工具 § Virtualenv 虛擬環境 17

Slide 18

Slide 18 text

Python 環境、套件安裝與使用 18 § Anaconda是一個免費開源的Python和R語言的發行版本,用於計 算科學,Anaconda致力於簡化包管理和部署。Anaconda的包使 用軟體包管理系統Conda進行管理。

Slide 19

Slide 19 text

pip 19

Slide 20

Slide 20 text

20 #Note. 套件管理⼯具:替開發者下載、保存第三⽅套件,在程式 中可以載⼊使⽤

Slide 21

Slide 21 text

21 #Note. 套件管理⼯具:替開發者下載、保存第三⽅套件,在程式 中可以載⼊使⽤ 1. 為什麼要用 pip? 2. pip 是從哪裡下載套件的? 3. 套件會被 pip 存放在哪?

Slide 22

Slide 22 text

執行位置 – 方法一 22 1.從開始找到 Anaconda 2. 點選 Prompt,打開黑色視窗 3.開始輸入 pip 指令

Slide 23

Slide 23 text

執行位置 – 方法二 23

Slide 24

Slide 24 text

相關的開發管理工具 § PIP 套件管理工具 § Pyenv 多版本Python管理工具 § Virtualenv 虛擬環境 24

Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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 ?

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Outline § Introduction § HelloWorld § Data Types & Operator § Flow Control § Function § Class § Exception § File IO 32

Slide 33

Slide 33 text

Common Types & Operator 33 Primitive Container

Slide 34

Slide 34 text

Primitive Types § Numeric type (int / float) § String type (str) § Boolean type (bool) 34

Slide 35

Slide 35 text

Built-in Functions 35 1 2 3 4 5 6 type() dir() help() https://docs.python.org/3/library/functions.html

Slide 36

Slide 36 text

Common Types & Operator 36 expression = operator (symbols)+ operand (variables)

Slide 37

Slide 37 text

Common Types & Operator 37 expression = operator (symbols)+ operand (variables) arithmetic comparison logical bitwise

Slide 38

Slide 38 text

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)) # print(type(b)) # print(type(c)) # print(isinstance(a, int)) # True print(isinstance(b, int)) # False

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

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...

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

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 四個輸⼊:

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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))

Slide 48

Slide 48 text

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]

Slide 49

Slide 49 text

String Type - Methods 49 1 2 3 4 5 6 7 8 9 10 b = 'hello world' dir(b)

Slide 50

Slide 50 text

String Type 50 1 2 3 4 5 6 7 8 9 10 split() find() replace() len() lower() upper() isdigit() isnumeric() isalpha()

Slide 51

Slide 51 text

§ Question:What is different among True, ‘True’, true ? 51

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

Try it! § #練習:⼀個網址的結構⼤概如圖所⽰,試著⽤ Python 分別把 每個值取出來。 55

Slide 56

Slide 56 text

#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}'

Slide 57

Slide 57 text

#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)

Slide 58

Slide 58 text

#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)

Slide 59

Slide 59 text

#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)

Slide 60

Slide 60 text

#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

Slide 61

Slide 61 text

§ Question:Why do I use Formatting String? 61

Slide 62

Slide 62 text

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

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

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}

Slide 66

Slide 66 text

List 66 § List – Operations § List – Index & Slice § List - Methods

Slide 67

Slide 67 text

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 # 不存在

Slide 68

Slide 68 text

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]

Slide 69

Slide 69 text

§ Question:How does arithmetical operation with string? 69

Slide 70

Slide 70 text

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]

Slide 71

Slide 71 text

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'

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

#Discussion 1. append, extend, + 三種方法有什麼不一樣? 2. reversed(L), L.reverse(), [::-1] 3. sorted(L), L.sort() 74

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

Tuple 76 § Tuple – Operations § Tuple – Index & Slice § Tuple – Destructuring & Swaping

Slide 77

Slide 77 text

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

Slide 78

Slide 78 text

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]

Slide 79

Slide 79 text

§ Question:How does arithmetical operation with string & list? 79

Slide 80

Slide 80 text

Destructuring & Swaping 80 1 2 3 4 5 6 7 8 9 10 (a, b) = my_list (a, b) = (b, a)

Slide 81

Slide 81 text

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

Slide 82

Slide 82 text

Dictionary 82 § Dictionary – Operations § Dictionary – Unordered to Ordered § Dictionary – Key Error

Slide 83

Slide 83 text

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']

Slide 84

Slide 84 text

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])

Slide 85

Slide 85 text

Dictionary – Key Error 85 1 2 3 4 5 6 7 8 9 10 my_dict['Tom'] # Traceback (most recent call last): # File "", line 1, in # 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}

Slide 86

Slide 86 text

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}

Slide 87

Slide 87 text

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.

Slide 88

Slide 88 text

Set 88 § Set – Operations

Slide 89

Slide 89 text

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}

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

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]

Slide 92

Slide 92 text

Container Types 92 § list [,] => Operations / Index & Slice / Methods § tuple (,) => Operations / Index & Slice /Destructuring & Swaping § dict {:,} => Operations / Unordered to Ordered / Key Error § set {,} => Operations

Slide 93

Slide 93 text

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 ?

Slide 94

Slide 94 text

94 Reference: https://www.linkedin.com/pulse/mutable-vs-immutable-objects-python-megha-mohan

Slide 95

Slide 95 text

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

Slide 96

Slide 96 text

iterator, iterable, iteration 96 Reference: http://nvie.com/posts/iterators-vs-generators/

Slide 97

Slide 97 text

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))

Slide 98

Slide 98 text

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))

Slide 99

Slide 99 text

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

Slide 100

Slide 100 text

Try it! § #練習:要求使⽤者輸⼊ n ,印出從 n 平⽅的對數值(Log) • hint:引入一個 math 的函式庫,並且利用 dir 與 math 查看 log 函式怎 麼使用 100

Slide 101

Slide 101 text

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

Slide 102

Slide 102 text

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

Slide 103

Slide 103 text

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

Slide 104

Slide 104 text

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

Slide 105

Slide 105 text

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

Slide 106

Slide 106 text

What it truth? 106

Slide 107

Slide 107 text

What it truth? 107

Slide 108

Slide 108 text

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 ...

Slide 109

Slide 109 text

109 Reference: http://swcarpentry.github.io/training-course/2013/03/concept-map-conditional-statements-python/ § operator • boolean/logical • comparison

Slide 110

Slide 110 text

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

Slide 111

Slide 111 text

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

Slide 112

Slide 112 text

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

Slide 113

Slide 113 text

Try it! § #練習:在數學中,用 n! 來表示階乘,例如,4! =1×2×3×4 =24。 請寫一個程式,讓使用者輸入 n,印出 n! 1. 用 for 迴圈完成 2. 用 while 迴圈完成 113

Slide 114

Slide 114 text

Try it! § #練習:如果將⼀句話作為⼀個字符串,那麼這個字符串中必然 會有空格(這裡只是討論英⽂),⽐如“How are you?”,但 有的時候,會在兩個單詞之間多⼤⼀個空格。現在的任務是,如 果⼀個字符串中有連續的兩個空格,請把它刪除。 114

Slide 115

Slide 115 text

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}

Slide 116

Slide 116 text

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']}

Slide 117

Slide 117 text

Try it! § #練習:畫各種三⾓形與變形 117 * ** *** **** * ** *** **** * *** ***** ******* * *** ***** ******* ********* ******* ***** *** *

Slide 118

Slide 118 text

§ https://leetcode.com/problems/two-sum/description/ 118

Slide 119

Slide 119 text

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

Slide 120

Slide 120 text

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)

Slide 121

Slide 121 text

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

Slide 122

Slide 122 text

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]

Slide 123

Slide 123 text

Try it! § #練習:建⽴⼀個 1 - 10 平⽅的數列。 123

Slide 124

Slide 124 text

Try it! § #練習:有兩個列表,分別是:a = [1,2,3,4,5],b = [9,8,7,6,5], 要計算這兩個列表中對應元素的和。 124

Slide 125

Slide 125 text

Try it! § #練習:有⼀個字典 ,myinfor = {"name":"qiwsir","site":"qiwsir.github.io","lang":"python"}, 將這 個字典變換成 :infor = {"qiwsir":"name","qiwsir.github.io":"site","python":"lang"} 125

Slide 126

Slide 126 text

Try it! § #練習:按照下⾯的要求實現對列表的操作,產⽣⼀個列表,其 中有40個元素,每個元素是0到100的⼀個隨機整數如果這個列表 中的數據代表著某個班級40⼈的分數,請計算成績低於平均分的 學⽣⼈數,並輸出對上⾯的列表元素從⼤到⼩排序 126

Slide 127

Slide 127 text

Try it! § #練習:承上題,想要對分數進⾏調整,不及格的⼈將原始分數 開根號乘以⼗(但最⾼不可以超過 60 分),及格者不變。 127

Slide 128

Slide 128 text

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

Slide 129

Slide 129 text

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

Slide 130

Slide 130 text

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})

Slide 131

Slide 131 text

Try it! § #練習:寫⼀個計算平⽅的函式。 131

Slide 132

Slide 132 text

Try it! § #練習:寫⼀個計算平⽅根的函式。 132

Slide 133

Slide 133 text

Try it! § #練習:寫⼀個回傳⼀次⽅,⼆次⽅,…,到指定次⽅的函式。 133

Slide 134

Slide 134 text

*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'})

Slide 135

Slide 135 text

**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}

Slide 136

Slide 136 text

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'}

Slide 137

Slide 137 text

137 Reference: http://swcarpentry.github.io/training-course/2013/05/concept-map-python-functions/

Slide 138

Slide 138 text

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")

Slide 139

Slide 139 text

Try it! § #練習:寫⼀個輸⼊ N 個數字,回傳總和的函式。 139

Slide 140

Slide 140 text

Try it! § #練習:印出 1~100 有哪些質數 140

Slide 141

Slide 141 text

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

Slide 142

Slide 142 text

Software Engineering 142 Procedural Programming Modular Programming Objective Orient Programming Functional Programming

Slide 143

Slide 143 text

Software Engineering 143 Modular Programming Objective Orient Programming

Slide 144

Slide 144 text

Class and Object 144

Slide 145

Slide 145 text

145 abstract instance

Slide 146

Slide 146 text

146 class object

Slide 147

Slide 147 text

147 class object State Behavior

Slide 148

Slide 148 text

148 class object Properties method

Slide 149

Slide 149 text

OOP Concept § Abstraction § Encapsulation => public, private § Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 149

Slide 150

Slide 150 text

Inheritance § base classes § derived class 150

Slide 151

Slide 151 text

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)

Slide 152

Slide 152 text

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)

Slide 153

Slide 153 text

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())

Slide 154

Slide 154 text

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

Slide 155

Slide 155 text

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

Slide 156

Slide 156 text

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

Slide 157

Slide 157 text

Try it! § #練習:建⽴⼀個 Student 的類別,要包含姓名、性別、年齡, 也要可以修改資料。 § class student() § det __init__(self, name, sex, age): § selt.name = name. § … 157

Slide 158

Slide 158 text

Try it! § #練習:利⽤上述建⽴的類別,宣告幾個物件,並放到⼀個 dict 保存。 § TomObj = student(‘Tom’, ‘male’, 22) § stduents = {‘Tom’: TomObj , ‘Mary’: obj} § stduents.Tom.age § stduents.Mary.age 158

Slide 159

Slide 159 text

OOP Concept § Abstraction § Encapsulation => public, private § Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 159

Slide 160

Slide 160 text

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())

Slide 161

Slide 161 text

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())

Slide 162

Slide 162 text

Inherit 162 1 2 3 4 5 6 7 8 9 10 class ExecutiveAccount( BankAccount ): def requestCredit(self, amount): self.balance += amount executive = ExecutiveAccount()

Slide 163

Slide 163 text

OOP Concept § Abstraction § Encapsulation => public, private § Inheritance § Polymorphism => 不同的類別,有相同的 method § Overloading => 一個類別中相同的 method ,有不同的行為 § Overriding => 父子相同的 method,改寫成不同的行為 163

Slide 164

Slide 164 text

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())

Slide 165

Slide 165 text

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())

Slide 166

Slide 166 text

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())

Slide 167

Slide 167 text

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

Slide 168

Slide 168 text

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

Slide 169

Slide 169 text

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 "", line 1, in ZeroDivisionError: division by zero 4 + spam*3 # Traceback (most recent call last): # File "", line 1, in NameError: name 'spam' is not defined '2' + 2 # Traceback (most recent call last): # File "", line 1, in TypeError: Can't convert 'int' object to str implicitly

Slide 170

Slide 170 text

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

Slide 171

Slide 171 text

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()

Slide 172

Slide 172 text

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

Slide 173

Slide 173 text

File Write 173 1 2 3 fh = open("example.txt", "w") fh.write(”hello world") fh.close()

Slide 174

Slide 174 text

File Read 174 1 2 3 fh = open("example.txt", ”r") fh.read() fh.close()

Slide 175

Slide 175 text

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()

Slide 176

Slide 176 text

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

Slide 177

Slide 177 text

Thanks for listening. 2017/08/07 (Tue.) Fundamental Python - Basic Wei-Yuan Chang [email protected] v123582.github.io