Python 程式設計研習
蘇東興、鄭明昌、楊珺宇
明新科大資工系
110/9/5
https://mustbeai.blogspot.com/p/python.html
1
內容
2
評量
3
1. 研習內容
4
週 | 研 習 內 容 | 備 註 |
1 | 開發環境 Anaconda介紹 Python資料型別、變數與運算 Python資料結構 list、set、dict、tuple Python 內建常用函數 | 安裝Anaconda 開發環境、使用Jupyter 開發介面 |
2 | 向量與矩陣運算-NumPy套件 資料處理分析-Pandas套件 檔案處理函數 | |
3 | 資料視覺化-Matplotlib 套件 | |
4 | 網頁爬蟲與 OpenData取得 |
Python 基本資料型態
5
Variable(變數)命名規則
6
變數命名規則
7
Python 保留字
Operator(運算子)
8
運算優先順序
9
Comment(註解)
Step 1:
Step 2:
’’’
10
運算範例
11
Python 物件
12
>>> x = 100
>>> id(x)
1573412672
>>> type(x)
<class 'int'>
>>> print(x)
100
數學函數
13
布林(Bool)運算範例
x = True
y = False
14
字串運算範例1/3
s1 = "學習Python語言程式設計"
s2 = 'Hello World!’
ch1 = "A"
ch2 = 'b'
15
字串運算範例2/3
str1 = 'hello' # 使用單引號建立字串
str2 = "python" # 使用雙引號建立字串
print(str1) # 顯示 "hello"
print(len(str1)) # 字串長度: 顯示 "5"
str3 = str1 + ' ' + str2 # 字串連接
print(str3) # 顯示 "hello python"
str4 = '%s %s %d' % (str1, str2, 12) # 格式化字串
print(str4) # 顯示 "hello python 12"
16
字串運算範例3/3
17
字串函數1/2
s = "hello“
dir(s) # 顯示 string 所有函數
print(s.capitalize()) # 第1個字元大寫: 顯示 "Hello"
print(s.upper()) # 轉成大寫: 顯示 "HELLO"
print(s.rjust(7)) # 右邊填空白字元: 顯示 " hello"
print(s.center(7)) # 置中顯示: 顯示 " hello "
print(s.replace('l', 'L')) # 取代字串: 顯示 "heLLo"
print(' python '.strip()) # 刪除空白字元: 顯示 "python"
18
字串函數2/2
19
數值與字串格式化 1/2
format(value[, spec])
參數spec的格式如下:
[[fill]align][sign][#][0][width][,][.precision][type]
20
>>> format(123, "^10")
' 123 '
>>> format(123, "$^10")
'$$$123$$$$'
>>> format(12345678, ",")
'12,345,678'
>>> format(65, "#b")
'0b1000001'
>>> format(123, "=+010")
'+000000123'
數值與字串格式化 2/2
21
>>> format(1234.5678, "10.2f")
' 1234.57'
>>> format(1234.5678, "10.2e")
' 1.23e+03'
>>> format(1234.5678, "<15.3f")
'1234.568 '
>>> format("Hello, World!", "20")
'Hello, World! '
>>> format("Hello, World!", ">20")
' Hello, World!'
>>> format("Hello, World!", "^20")
' Hello, World! '
字串- (escape sequence)
22
Esc Seq | 意 義 |
\\ | 印出反斜線 (\) |
\' | 印出單引號 (') |
\" | 印出雙引號 (") |
\a | 響鈴 (Bell) |
\b | 倒退鍵 (Backspace) |
\f | 換頁 (Formfeed) |
\n | 換行 (Linefeed) |
\r | 歸位 (Carriage Return) |
\t | [Tab] 鍵 (Horizontal Tab) |
\v | 垂直定位 (Vertical Tab) |
\ooo | ASCII字元 (ooo為八進位整數) |
\xhh | ASCII字元 (hh為十六進位整數) |
\N{name} | Unicode字元 (name為字元名稱) |
\uxxxx | Unicode字元 (xxxx為16-bit十六進位整數) |
\Uxxxxxxxx | Unicode字元 (xxxxxxxx為32-bit十六進位整數) |
print("\"Python\"程式設計")
"Python"程式設計
print("\101")
A
print("\x41")
A
print("\u0041")
A
print ("\N{BLACK SPADE SUIT}")
♠
Print-format
23
print("Hello World") #Hello World
a = 1
b = 'runoob‘
print(a,b) #1 runoob
print("aaa""bbb") #aaabbb
print("aaa","bbb") #aaa bbb
print("www","runoob","com",sep=".") # www.runoob.com
print(“%10d“%10) #靠右對齊
print(“%+10d“%10) #靠右對齊
print(“%-10d“%10) #靠左對齊
print(“% 10d“%10) #左側填空白
print(“%010d“%10) #左側填0
Print-format
24
print(“%7.3f“%12.34567)
print(“%7.3f“%2.34567)
print(“%7.3f“%11112.34567)
print(“%.*f“%(3, 2.34567)
# 12.345
# 2.345
#11112.345
#2.345
text = '%d %.2f %s' % (1, 99.3, 'Justin')�print(text)�#1 99.30 Justin�print('%d %.2f %s' % (1, 99.3, 'Justin'))�#1 99.30 Justin
Print-format
25
print("I'm %s. I'm %d year old" % (‘Chang', 30))
a = "I'm %s. I'm %d year old" % (‘Chang', 30)
print(a)
print("I'm %(name)s. I'm %(age)d year old" % {'name':'Vamei', 'age':99})
print(‘’Hello World‘’, end=‘’‘’) #不換行
print('', Same Line'')
print(‘’Hello World‘’, end=‘’,‘’) #不換行,加 “,”
print(''Same Line'')
Print-format
26
print('{0} is {1}!!'.format(‘Chang', ‘goodman'))�#Chang is goodmanar!!�print('{real} is {nick}!!'.format(real = ' Chang ', nick = ' goodman '))�#Chang is goodmanar!!�print( '{real} is {nick}!!'.format(nick = ' goodman ', real = ' Chang '))�#Chang is goodmanar!!�print('{0} is {nick}!!'.format(' Chang ', nick = ' goodman '))�#Chang is goodmanar!!�print('{name} is {age} years old!'.format(name = ' Chang ', age = 35))�#Chang is 35 years old!'
Print-format-repr
27
from datetime import datetime
now = datetime.now()
print(str(now)) #2017-04-22 15:41:33.012917
print(repr(now)) #datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)
raw = ‘\n\t This is a \t line with format \t\n’
print(raw)
raw =r‘\n\t This is a \t line with format \t\n’
print(raw)
raw = repr(‘\n\t This is a \t line with format \t\n’)
print(raw)
#
# This is a line with format
#\n\t This is a \t line with format \t\n
#‘\n\t This is a \t line with format \t\n’
Print-format
28
流程控制
29
條件控制 – if條件敘述
30
s = int(input("請輸入成績 => "))
if s >= 60:
print("成績及格!")
else:
print("成績不及格!")
t = int(input("請輸入氣溫 => "))
if t < 20:
print("加件外套!")
print("今天氣溫 = " + str(t))
a = int(input("請輸入年齡 => "))
if a < 13:
print("兒童")
elif a < 20:
print("青少年")
else:
print("成年人")
條件控制 – 單行條件敘述
變數 = 變數1 if 條件運算式 else 變數2
h = h-12 if h >= 12 else h
31
迴圈(loop) 1/4
32
m = int(input('m: '))
s = 0
for i in range(1, m + 1):
s = s + i
print("總和 = " + str(s))
for i in range(5):
print(i,end”,”)
# 0,1,2,3,4
for i in range(2,6):
print(i,end”,”)
# 2,3,4,5
m = int(input('m: '))
s = 0
for i in range(1, m + 1, 2):
s = s + i
print("總和 = " + str(s))
迴圈(loop) 2/4
33
list1 = [15, 20, 33, 7, 8]
sum = 0
for i in list1:
sum = sum + i
print(“Sum:", sum)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print (‘fruit:', fruit )
#fruit:banana
#fruit:apple
#.......
for letter in 'Python':
print('char :', letter)
#char:P
#char:y
#....
迴圈(loop) 3/4
34
n = int(input("請輸入大於 1 的整數:"))
if(n == 2):
print("2 是質數!")
else:
for i in range(2, n):
if(n % i == 0):
print("%d is not prime!" % n)
break
else:
print("%d is prime!" % n)
for i in range(1,10):
for j in range(1,10):
product = i * j
print("%d*%d=%-2d " % (i, j, product), end="")
# -2d 靠左對齊
print()
迴圈(loop) 4/4
35
cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� break� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)
cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� continue� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)
cnt=0�for c in ‘content’:� cnt+=1� if c == ‘t’:� pass� print(c)��print(‘\n迴圈結束')�print(‘執行 %d 次' %cnt)
迴圈控制 – while條件迴圈
36
n = int(input(" n:"))
r = 1
m = 1
while m <= n:
r = r * m
m = m + 1
print(" n! = " + str(r))
count = 0
while count < 3:
print (count, " is less than 3" )
count = count + 1
else:
print (count, " is not less than 5“)
#0 is less than 3
#1 is less than 3
#2 is less than 3
#3 is not less than 3
函數-定義
37
函數-定義 與呼叫
38
def print_msg(): # 無參數函數 print(“Hello Python!") | def is_valid_num(no): if no >= 0 and no <= 200.0: return True else: return False | def convert_to_f(c): f = (9.0 * c) / 5.0 +32 return c, f |
print_msg() | if is_valid_num(100): print("合法!") else: print("不合法") | c, f = convert_to_f(32) print(“c,f:”,c,f) |
函式的參數
39
def swap(x, y):
temp = x
x = y
y = temp
a, b = 1, 2
print(a, b)
swap(a, b)
print(a, b)
def swap(x):
temp = x[0]
x[0] = x[1]
x[1] = temp
a = [1, 2]
print(a)
swap(a)
print(a)
關鍵字引數
40
def trapezoidArea(top, bottom, height):
result = (top + bottom) * height / 2
print("這個梯形面積為", result)
trapezoidArea(10, 20, 5)
trapezoidArea(10, height = 5, bottom = 20)
trapezoidArea(height = 5, bottom = 20, top = 10)
預設引數值
41
def teaTime(dessert, drink = "紅茶"):
print("我的甜點是", dessert, ",飲料是", drink)
teaTime("馬卡龍", "咖啡")
teaTime("帕尼尼")
teaTime(dessert = "三明治", drink = "奶茶")
teaTime("紅豆餅", drink = "綠茶")
任意引數串列
42
def add(*numbers):
total = 0
for i in numbers:
total = total + i
return total
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 2, 3, 4))
print(add(1, 2, 3, 4, 5))
lambda運算式
Python提供lambda關鍵字用來建立小的匿名函式,其語法如下:
lambda arg1, arg2, …: expression
43
add = lambda x, y: x + y
print(add(1, 2))
3
print(add(50, -100))
-50
print(add(50, 3.8))
53.8
print(add(50, True))
51
print(add("abc", "de"))
abcde
Python模組與套件
44
使用Python模組與套件 – �匯入模組或套件
45
import random
list = [20, 16, 10, 5]
random.shuffle(list)
print( "随机排序列表 : ", list)
random.shuffle(list)
print ("随机排序列表 : ", list )
import random
target = random.randint(1, 100)
Target = random.random()
import random as r
target = r.randint(1,100)
from bs4 import BeautifulSoup
html_str = "<p>Hello World!</p>"
soup = BeautifulSoup(html_str, "lxml")
print(soup)
from random import seed, random
seed(100)
target = random(1,100)
from random import *
seed(100)
target = random
Contaoner(容器)型態
46
list
47
List-基本用法
ls = list() #建立空list
ls = [] #建立空list
ls = list[1,2,3] # 建立清單
ls = [6,4,5] # 建立清單
print(ls, ls[2]) # 顯示 "[6, 4, 5] 5"
print(ls[-1]) # 負索引從最後開始: 顯示 "5"
ls[2] = "py" # 指定字串型態的項目
print(ls) # 顯示 "[6, 4, 'py']"
ls.append("bar") # 新增項目
print(ls) # 顯示 "[6, 4, 'py', 'bar']"
ele = ls.pop() # 取出最後項目
print(ele, ls) # 顯示 "bar [6, 4, 'py']"
48
List-split
nums = list(range(5)) # 建立一序列的整數清單
print(nums) # 顯示 "[0, 1, 2, 3, 4]"
print(nums[2:4]) # 切割索引2~4(不含4): 顯示 "[2, 3]"
print(nums[2:]) # 切割索引從2至最後: 顯示 "[2, 3, 4]"
print(nums[:2]) # 切割從開始至索引2(不含2): 顯示 "[0, 1]"
print(nums[:]) # 切割整個清單: 顯示 "[0, 1, 2, 3, 4]"
print(nums[:-1]) # 使用負索引切割: 顯示 "[0, 1, 2, 3]"
nums[2:4] = [7, 8] # 使用切割來指定子清單
print(nums) # 顯示 "[0, 1, 7, 8, 4]"
49
List-loop
animals = ['cat', 'dog', 'bat']
for animal in animals:
print(animal)
for index, animal in enumerate(animals):
print(index, animal)
50
List- Functions
51
List
52
二維list
53
01 grades = [[85, 95, 90], [96, 92, 85], [88, 78, 86], [88, 80, 82], [80, 78, 75]]
02 for i in range(5):
03 subTotal = 0
04 for j in range(3):
05 subTotal += grades[i][j]
06 grades[i].append(subTotal)
07
08 for i in range(5):
09 print(“學生”, i + 1, “的總分是", grades[i][3])
Dic-字典
print(d["cat"]) # 使用Key取得項目: 顯示 "white"
print("cat" in d) # 是否有Key: 顯示 "True"
d["pig"] = "pink" # 新增項目
print(d["pig"]) # 顯示 "pink"
print(d.get("monkey", "N/A")) # 取出項目+預設值: 顯示 "N/A"
print(d.get("pig", "N/A")) # 取出項目+預設值: 顯示 "pink"
del d["pig"] # 使用Key刪除項目
print(d.get("pig", "N/A")) # "pig"不存在: 顯示 "N/A"
54
Dic-探索字典
55
d = {"chicken": 2, "dog": 4, "cat": 4, "spider": 8}
for animal in d:
legs = d[animal]
print(animal, legs)
d = {"chicken": 2, "dog": 4, "cat": 4, "spider": 8}
for animal, legs in d.items():
print("動物: %s 有 %d 隻腳" % (animal, legs))
Dic – loop
d1 = {x:x*x for x in range(10)}
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
d2 = {x:x*x for x in range(10) if x % 2 == 1}�#{1: 1, 3: 9, 9: 81, 5: 25, 7: 49}。
56
Set – 集合的基本使用
animals = {"cat", "dog", "pig"} # 建立集合
print("cat" in animals) # 檢查是否有此元素: 顯示 "True"
print("fish" in animals) # 顯示 "False"
animals.add("fish") # 新增集合元素
print("fish" in animals) # 顯示 "True"
print(len(animals)) # 元素數: 顯示 "4"
animals.add("cat") # 新增存在的元素
print(len(animals)) # 顯示 "4"
animals.remove('cat') # 刪除集合元素
print(len(animals)) # 顯示 "3"
57
Set – 探索集合
animals = {"cat", "dog", "pig", "fish"} # 建立集合
for index, animal in enumerate(animals):
print('#%d: %s' % (index + 1, animal))
58
Set – 集合運算
59
Tuple
t = (5, 6, 7, 8) # 建立元組
print(type(t)) # 顯示 "<class 'tuple'>"
print(t) # 顯示 "(5, 6, 7, 8)"
print(t[0]) # 顯示 "5"
print(t[1]) # 顯示 "6"
print(t[-1]) # 顯示 "8"
print(t[-2]) # 顯示 "7"
for ele in t: # 走訪項目
print(ele, end=" ") # 顯示 "5, 6, 7, 8"
60
61
The End