Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Python Fundamentals - Basic
2017/08/08 (Tue.)
WeiYuan
site: v123582.github.io
line: weiwei63
§ 全端⼯程師 + 資料科學家
略懂⼀點網站前後端開發技術,學過資料探勘與機器
學習的⽪⽑。平時熱愛參與技術社群聚會及貢獻開源
程式的樂趣。
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
3
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
4
Introduction
§ The Zen of Python: Beautiful, Explicit, Simple
§ Python 2.x or Python 3.x ?
§ Environment: `python --version`
§ Runtime: shell, command, jupyter/ipython, anaconda
§ IDE: pycharm, spider(built in anaconda)
§ PIP: library manager of python
5
6
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
7
Hello World
§ Encoding Declaration
§ Syntax
§ Import
§ Variable and Assignment
§ Indentation and Block
§ Input and Output (I/O)
§ Comment and Docstring
§ Function and Method
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# encoding: utf-8
import this
from keyword import kwlist
# ['False', 'None' . . .]
keywords = kwist
if len(keywords) > 0:
print(keywords)
x = input("Input Something...")
print("%s", % (x))
help(print)
Outline
§ Introduction
§ HelloWorld
§ Data Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
9
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression => operator + operand
§ String type
§ Container type
• list, tuple, dict, set
10
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression => operator + operand
§ String type
§ Container type
• list, tuple, dict, set
11
§ expression = operator + operand (varibles)
• arithmetic, comparison
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression => operator + operand
§ String type
§ Container type
• list, tuple, dict, set
12
§ expression = operator + operand (varibles)
• arithmetic, comparison
arithmetic
comparison
logical
bitwise
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression
§ String type
§ Container type
• list, tuple, dict, set
13
1
2
3
4
5
6
7
8
9
10
a = 20
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'bool'>
print(type(d)) # <class 'complex'>
print(isinstance(a, int)) # True
print(isinstance(b, int)) # False
# True, False
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression
§ String type
§ Container type
• list, tuple, dict, set
14
1
2
3
4
5
6
7
8
9
10
11
12
13
4 + 2 # 6
4.0 + 2 # 6.0
4.0 + 2.0 # 6.0
2 / 5 # 0 # 0.4
2.0 / 5 # 0.4
2 / 5.0 # 0.4
2.0 / 5.0 # 0.4
2 // 5 # 0
int(4.0) # 4
float(4) # 4.0
Common Types & Operator
§ Numeric type
• int, float, bool, complex
• expression
§ String type
§ Container type
• list, tuple, dict, set
15
1
2
3
4
5
6
7
8
9
w = 49
h = 163
bmi = 49 / (163/100)**2
print(bmi) # 49
w = 49.0
h = 163.0
bmi = 49 / (163/100)**2
print(bmi) # 18.4425...
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
16
Try it!
§ #練習:計算下列運算:
17
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)
flaot(1 + 3 // 2 **2)
Try it!
§ #練習:Add two Numbers
18
1
2
3
4
5
6
7
8
9
1
0
1
1
a = input()
b = input()
…
print('The sum of {0} and {1} is {2} '.format(a, b, sum))
Try it!
§ #練習:Find the Square Root
19
1
2
3
4
5
6
7
8
9
1
0
1
1
num	=	8
…
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Common Types & Operator
§ Numeric type
• int, float, bool, complex
§ String type
• len, lower, upper, split
§ Container type
• list, tuple, dict, set
20
1
2
3
4
5
6
7
8
a = '12345'
b = 'hello world'
c = 'n'
d = r'n'
print(b + str(a) + c + d)
print(b + str(a) + str(c) + str(d))
print(b + str(a) + repr(c) + repr(d))
Try it!
§ #練習:Set the following variables to their respective phrases:
1. Set caesar to Graham
2. Set sentence to There's a snake in my boot!
3. Set paragraph to Dear Mr. Chen,
I’m Jacky, nice to meet you.
21
Common Types & Operator
§ Numeric type
• int, float, bool, complex
§ String type
§ Container type
• list [] => mutable sequence
• tuple (,) => immutable sequence
• dict {:} => mutable unordered collection of key-value mapped element
• set {} => mutable unordered collections of unique elements
22
list
23
1
2
3
4
5
6
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
§ Question:How does arithmetical operation with string?
24
list
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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]
my_list[::-1] # [2, 3]
len(my_list) # 2
sum(my_list) # 5
my_list.count(2) # 1
', '.join(my_list) # '2, 3'
Try it!
§ #練習:有一個列表,其中包括 10 個元素,例如這個列表是 [1,
2, 3, 4, 5, 6, 7, 8, 9, 0],要求將列表中的每個元素一次向前移動一
個位置,第一個元素到列表的最後,然後輸出這個列表。最終樣
式是 [2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
26
Try it!
§ #練習:Sort Words in Alphabetic Order
27
1
2
3
4
5
6
7
8
9
1
0
1
1
my_str = "Hello this Is an Example With cased letters”
…
# ['Example', 'Hello', 'Is', 'With', 'an', 'cased',
'letters', 'this']
tuple
28
1
2
(a, b) = my_list
(a, b) = (b, a)
Try it!
§ #練習:Swap Two Variables
29
dict
30
1
2
3
4
5
6
7
8
9
10
11
12
my_dict = {'Mark': 1, 'test': 0}
my_dict['Mary'] = 2
del my_dict['test']
my_dict.items()
# dict_items([('Mark', 1), ('Mary', 2) ])
my_dict.keys()
# dict_keys(['Mark', 'Mary'])
my_dict.values()
# dict_values([1, 2])
dict
31
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: 'openhome’
my_dict.get('Tom', ''), my_dict
# '', {'Mark': 1, 'test': 0}
my_dict.setdefault('Tom', 3), my_dict
# 3, {'Tom': 3, 'Mark': 1, 'test': 0}
set
32
1
2
3
4
5
6
7
8
9
admins = {'admin'}
users = {'admin', 'user1', 'user2'}
'Justin' in admins # True
admins & users # {'admin'}
admins | users # {'admin', 'user1', 'user2'}
admins - users # {}
admins ^ users # {user1, user2}
Try it!
§ #練習:Illustrate Different Set Operations
33
1
2
3
4
5
6
7
8
9
10
# define three sets
E, N = {0, 2, 4, 6, 8}, {1, 2, 3, 4, 5}
print("Union of E and N is",E | N) #
print("Intersection of E and N is",E & N)
print("Difference of E and N is",E - N)
print("Symmetric difference of E and N is",E ^ N)
34
§ 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 ?
35Reference:	https://www.linkedin.com/pulse/mutable-vs-immutable-objects-python-megha-mohan
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)
36
iterator, iterable, iteration
37Reference:	http://nvie.com/posts/iterators-vs-generators/
iterator, iterable, iteration
38
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))
iterator, iterable, iteration
39
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))
bulit-in method
40
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
Try it!
§ #練習:要求使⽤者輸⼊ n ,印出從 n 平⽅的對數值(Log)
• hint:引入一個 math 的函式庫,並且利用 dir 與 math 查看 log 函式怎
麼使用
41
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
42
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
43
Flow Control
§ Logical Operator
§ Comparison Operator
44
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
Flow Control
§ Logical Operator => return Boolean
§ Comparison Operator => return Boolean
45
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
What it truth?
46
What it truth?
47
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
48
1
2
3
4
5
6
7
8
9
if condition:
...
elif condition:
...
else:
...
a = ... if condition else ...
49Reference:	http://swcarpentry.github.io/training-course/2013/03/concept-map-conditional-statements-python/
§ operator
• boolean/logical
• comparison
Try it!
§ #練習:承上題,如果要把偶數放前⾯,奇數放後⾯該怎麼做?
結果像是 [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
50
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
51
1
2
while condition:
....
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
52
1
2
3
4
5
for i in [...]:
...
a = [i for i in [...]] # list
b = (i for i in [...]) # generator
Try it!
§ #練習:在數學中,用 n! 來表示階乘,例如,4! =1×2×3×4 =24。
請計算 3!, 4!, 5!。請寫一個程式,讓使用者輸入 n,印出 n!
1. 用 for 迴圈完成
2. 用 while 迴圈完成
53
Try it!
§ #練習:如果將⼀句話作為⼀個字符串,那麼這個字符串中必然
會有空格(這裡只是討論英⽂),⽐如“How are you?”,但
有的時候,會在兩個單詞之間多⼤⼀個空格。現在的任務是,如
果⼀個字符串中有連續的兩個空格,請把它刪除。
54
Try it!
§ #練習:"Please count the character here."
55
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}
Try it!
§ #練習:"Here are UPPERCASE and lowercase chars."
56
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']}
Try it!
§ #練習:畫各種三⾓形與變形
57
*
**
***
****
*
**
***
****
*
***
*****
*******
*
***
*****
*******
*********
*******
*****
***
*
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
58
Flow Control
§ if - elif - else
§ while
§ for in
§ break, continue, pass
§ range(), zip(), enumerate()
59
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)
More zip() …
60
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
More zip() …
61
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]
Try it!
§ #練習:在数学中,⽤n!来表⽰阶乘。例如,4!=1×2×3×4=24。
如果将n个物体排列,有多少种排列⽅式,那就是n!。根据定义,
0!=1。
62
Try it!
§ #練習:建⽴⼀個 1 - 10 平⽅的數列。
63
Try it!
§ #練習:有兩個列表,分別是:a = [1,2,3,4,5],b = [9,8,7,6,5],
要計算這兩個列表中對應元素的和。
64
Try it!
§ #練習:有⼀個字典 ,myinfor =
{"name":"qiwsir","site":"qiwsir.github.io","lang":"python"}, 將這
個字典變換成 :infor =
{"qiwsir":"name","qiwsir.github.io":"site","python":"lang"}
65
Try it!
§ #練習:按照下⾯的要求實現對列表的操作,產⽣⼀個列表,其
中有40個元素,每個元素是0到100的⼀個隨機整數如果這個列表
中的數據代表著某個班級40⼈的分數,請計算成績低於平均分的
學⽣⼈數,並輸出對上⾯的列表元素從⼤到⼩排序
66
Try it!
§ #練習:承上題,想要對分數進⾏調整,不及格的⼈將原始分數
開根號乘以⼗(但最⾼不可以超過 60 分),及格者不變。
67
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
68
Function
69
1
2
3
4
5
6
7
8
9
max1 = a if a > b else b...
max2 = x if x > y else y...
def max(a, b):
return a if a > b else b
maximum = max
maximum(10, 20)
# 20
Basic Method for Call Function
70
1
2
3
4
5
6
7
def f(x, y):
return x, y
f(1, 2)
f(y=2, x=1)
f(*(1, 2))
f(**{y=2, x=1})
Try it!
§ #練習:寫⼀個計算平⽅的函式。
71
Try it!
§ #練習:寫⼀個計算平⽅根的函式。
72
Try it!
§ #練習:寫⼀個回傳⼀次⽅,⼆次⽅,…,到指定次⽅的函式。
73
*args
74
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'})
**kargs
75
1
2
3
4
5
def foo(**kargs):
print(kargs)
foo(a=1,b=2,c=3)
# {'a': 1, 'c': 3, 'b': 2}
type1 + type2 + type3
76
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'}
77Reference:	http://swcarpentry.github.io/training-course/2013/05/concept-map-python-functions/
Try it!
§ #練習:以下程式會如何輸出?
78
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")
Try it!
§ #練習:寫⼀個輸⼊ N 個數字,回傳總和的函式。
79
Try it!
§ #練習:每次考試之後,教師都要統計考試成績,⼀般包括:平
均分,對所有⼈按成績從⾼到低排隊,誰成績最好,誰成績最差
還有其它的統計項,暫且不 為了簡化,以字典形式表⽰考試成績
記錄,例如:{“zhangsan”:90,“lisi” :78,
“wangermazi”:39},當然,也許不能這三項,可能還有,
每個⽼師所在處理的內容稍有不同,因此字典裡的鍵值對也不⼀
樣。怎麼做?有幾種可能要考慮到:最⾼分或者最低分,可能有
⼈並列。要實現不同⾧度的字典作為輸⼊值。輸出結果中,除了
平均分,其它的都要有姓名和分數兩項,否則都匿名了,怎麼刺
激學渣,表揚學霸呢?
80
Try it!
§ #練習:印出 1~100 有哪些質數
81
Try it!
§ #練習:簡單計算機實現
82
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
83
Definition
84
1
2
3
4
5
6
7
8
class Animal():
def __init__(self, name):
self.name = name
def call():
pass
a = Animal('動物')
print(a.name)
Try it!
§ #練習:建⽴⼀個 Student 的類別,要包含姓名、性別、年齡,
也要可以修改資料。
§ calss student()
§ det __init__(self, name, sex, age):
§ selt.name = name.
§ …
85
Try it!
§ #練習:利⽤上述建⽴的類別,宣告幾個物件,並放到⼀個 dict
保存。
86
Inherit
87
1
2
3
4
5
6
7
8
9
10
class Dog(Animal):
def __init__(self, name, age):
super().__init__('小狗'+name)
self.age = age
def call(self):
print('汪汪汪')
d = Dog('小白', 13)
print(d.name)
Try it!
§ #練習:承上題,繼承 Student 類別,建⽴⼀個 ClassLeader 的
⼦類別。
88
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
89
Error Exception
90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
10 * (1/0)
4 + spam*3
'2' + 2
Error Exception
91
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
try-except
92
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)
else:
pass
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
Finally
93
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
else:
do something
finally
do something
try:
file = open("test.py")
except:
print('Read file error')
finally:
file.close()
Outline
§ Introduction
§ HelloWorld
§ Common Types & Operator
§ Flow Control
§ Function
§ Class
§ Exception
§ File IO
94
File Write
95
1
2
3
fh = open("example.txt", "w")
fh.write(”hello world")
fh.close()
File Read
96
1
2
3
fh = open("example.txt", ”r")
fh.read()
fh.close()
With
97
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()
mode
98
r 以只读⽅式打开⽂件。⽂件的指针将会放在⽂件的开头。这是默认模式。
r+ 打开⼀个⽂件⽤于读写。⽂件指针将会放在⽂件的开头。
w 打开⼀个⽂件只⽤于写⼊。如果该⽂件已存在则将其覆盖。如果该⽂件不存
在,创建新⽂件。
w+ 打开⼀个⽂件⽤于读写。如果该⽂件已存在则将其覆盖。如果该⽂件不存在,
创建新⽂件。
a 打开⼀个⽂件⽤于追加。如果该⽂件已存在,⽂件指针将会放在⽂件的结尾。
也就是说,新的内容将会被写⼊到已有内容之后。如果该⽂件不存在,创建
新⽂件进⾏写⼊。
a+ 打开⼀个⽂件⽤于读写。如果该⽂件已存在,⽂件指针将会放在⽂件的结尾。
⽂件打开时会是追加模式。如果该⽂件不存在,创建新⽂件⽤于读写。
Thanks for listening.
2017/08/07 (Tue.) Fundamental Python - Basic
Wei-Yuan Chang
v123582@gmail.com
v123582.github.io

More Related Content

Python fundamentals - basic | WeiYuan