學習總成果整理
===
輸入與輸出
---
```python
name=str(input("請輸入名字:")) #輸入
print(name) #一般輸出
print("你的名字是{}".format(name)) #format() method
print(f"你的名字是{name}") #格式化的字串文本
```
布林邏輯與選擇結構
---
```python
#布林值(booling)只有兩種型態
a = True
b = False
#條件運算子
1==1 #等於,True
1!=1 #不等於,False
1>1 #大於,False
1>=1 #大於等於,True
1<1 #小於,False
1<=1 #小於等於,True
#邏輯運算子
1==1 and 2>1 #全部符合,True
1==1 or 2<1 #部分符合,True
not 1==1 #取非結果,False
```
```python
#if-elif-else 選擇結構
x=int(input("請輸入數字:"))
if x>0:
print(f"{x}為正數")
elif x<0:
print(f"{x}為負數")
else:
print(f"{x}為0")
```
重複結構
---
```python
#for-loop
for i in range(1,11):
print(i,end=' ')
#輸出為1 2 3 4 5 6 7 8 9 10
# while-loop
count=0
while count<5:
print(count)
count+=1
#輸出為01234
#使用continue可跳過此迴圈
#使用break可直接中斷跳出此迴圈
```
函數的定義與應用
---
```python
#定義計算bmi的函數
def bmi(a,b):
num=a/(b**2)
num=round(num,2)
print(num)
n=int(input("請輸入體重(kg):"))
m=int(input("請輸入身高(cm):"))
m=m/100
bmi(n,m) #調用bmi函數
```
檔案及例外處理
---
```python
try:
file=open('python作業.txt','r')
#'r'為唯讀模式,'w'為覆寫模式,'a'為續寫模式
content=file.read() #開始讀取
print("文字檔案內容為:")
print(content)
file.close() #關閉檔案
#進行例外處理
except FileNotFoundError:
print("找不到指定的檔案。")
except PermissionError:
print("沒有權限讀取該檔案。")
except:
print("出現未知的錯誤。")
finally:
print("已嘗試讀取檔案。")
file.close()
```
列表(List)、元組(Tuple)
---
```python
#列表(List):可變
list1=[1,2,3,'a','b','c']
#在末尾添加新的元素
list1.append('d') #[1, 2, 3, 'a', 'b', 'c', 'd']
#在指定處插入新元素
list1.insert(1,1.5) #[1, 1.5, 2, 3, 'a', 'b', 'c', 'd']
#將另一個列表的所有元素移至列表末尾
list1.extend(['e','f']) #[1, 1.5, 2, 3, 'a', 'b', 'c', 'd', 'e', 'f']
#移除列表中的指定值的第一個匹配項
list1.remove(1.5) #[1, 2, 3, 'a', 'b', 'c', 'd', 'e', 'f']
#刪除列表中指定索引位置的元素
del list1[8] #[1, 2, 3, 'a', 'b', 'c', 'd', 'e']
#移除列表中指定位置的元素(預設為最後一個)
list1.pop() #[1, 2, 3, 'a', 'b', 'c', 'd']
#元組(Tuple):不可變
tuple2=(1,2,3,'a','b','c')
print(tuple2) #(1, 2, 3, 'a', 'b', 'c')
```
資料視覺化
---
```python
import matplotlib.pyplot as plt #引入Matplotlib模組
#創建數據
x=[1,2,3,4,5]
y=[2,3,5,7,11]
plt.plot(x, y) #折線圖
plt.bar(x, y) #長條圖
plt.hist(x, y) #直方圖
plt.boxplot(x, y) #箱型圖
plt.scatter(x, y) #散布圖
#細節調整
plt.xlabel("年份") #X軸標籤
plt.ylabel("人數") #Y軸標籤
plt.title("每年遊樂園買票的人數") #標題
plt.show() #顯示圖形
```
字典(dictionary)、集合(set)
---
```python
#字典(dictionary)
#鍵值無序唯一、內容可變
student={"name":"Ethan","age":"17","gender":"male"} #創建一個dictionary
student["age"]=18 #修改字典中的值
student["city"]="New York" #新增鍵值對
del student["gender"] #刪除鍵值對
print(len(student)) #搜尋鍵值對數量
for a in student:
print(a) #輸出字典中的鍵
for b in student.values():
print(b) #輸出字典中的值
for a,b in student.items():
print(f"{a}:{b}") #輸出字典中的鍵值對
```
```python
#集合(set)
#元素無序、不重複、可變
set1={1,2,3}
set2={4,5,6} #創建集合
set1.add(4) #增加某項元素
set2.remove(6) #移除某項元素
set2.discard(7) #不引發錯誤的移除
print(set1 & set2) #交集 輸出{4}
print(set1 | set2) #聯集 輸出{1, 2, 3, 4, 5}
print(set1 - set2) #差集 輸出{1, 2, 3}
print(set1 ^ set2) #對稱差集 輸出{1, 2, 3, 5}
```
文字處理與爬蟲程式
---
```python
#NLTK(Natural Language Toolkit)
#NLTK是Python的一個自然語言處理庫,提供了許多用於文本分析和處理的工具和數據集。
import nltk
from collections import Counter
#分詞(tokenization)
text = "My name is Ethan."
tokens = nltk.word_tokenize(text)
print(tokens)
#輸出 ['My', 'name', 'is', 'Ethan', '.']
#計算單字出現次數
def count_words(words):
#計算單詞出現次數
word_counts=Counter(words)
return word_counts
print("單詞出現次數:")
word_counts = count_words(tokens)
for word,count in word_counts.items():
print(f"{word}:{count}次")
#爬蟲程式:自動抓取網路資料的過程
#步驟:1.請求網頁內容 2.抓取所需資料 3.儲存資料
#應用:1.爬遍所有飯店網站,找出最划算的房間 2.定期監測特定商品價格,當有特價時,即時通知
```
物件定義與應用
---
```python
#定義類別(class)
class Person:
def __init__(self,name,age):
self.a=name
self.b=age
#創建一個類別
person1=Person("Ethan",17)
print(person1.a) #輸出:Ethan
print(person1.b) #輸出:17
print(f"我的名字是{person1.a},我{person1.b}歲。")
#輸出:我的名字是Ethan,我17歲。
```
Python與代數
---
```python
#SymPy是一個Python庫,用於執行符號計算。特別適合用來學習和教學微積分。
import sympy as sp
x=sp.Symbol('x') #定義符號變量
#解方程式(以一元
solutions=sp.solve(sp.Eq(x**2-4,0),x)
print("x的解為:",solutions)
#輸出 x的解為:[-2, 2]
```
Python與微積分
---
```python
#SymPy是一個Python庫,用於執行符號計算。特別適合用來學習和教學微積分。
import sympy as sp
x=sp.symbols("x") #定義符號變量
f=x**2+3*x+2 #定義函數
#微分
f_differentiation=sp.diff(f,x)
print("f的一階導函數為:",f_differentiation)
#輸出 f的一階導函數為:2*x + 3
#積分
f_integration=sp.integrate(f,x)
print("f的反導函數為:",f_integration)
#輸出 f的反導函數為:x**3/3 + 3*x**2/2 + 2*x
```