# Python 入門
[Google Colab 教材](https://colab.research.google.com/drive/1kS8MKXbLGnzgibJCmjTgn1rt8A-wyUhq?usp=sharing)
## 本機安裝 python
- **前置步驟**
- **移除 windows 應用程式執行別名關聯**
設定 > 應用程式與功能 > 應用程式執行別名


移除python.exe的別名
- **安裝**
- **下載 python**
https://www.python.org/downloads/
- **安裝 python**

- **試試看吧**
- **一段把電腦關機的程式**
```python
import os
os.system('shutdown /s')
```
## 第一章:Python基礎
### 什麼是Python?
- **簡單介紹**
- Python是一種高級編程語言,創建於1991年,由Guido van Rossum設計。
- 它以簡潔和可讀性強的語法而聞名,非常適合初學者。
- **為什麼選擇Python?**
- 易學易用:Python語法簡單明瞭,非常適合編程初學者。
- 強大的社區和豐富的資源:Python有大量的開源庫和框架,涵蓋了從數據科學到網頁開發的各個領域。
- 數據科學:pandas、numpy 和 matplotlib 使得數據處理和可視化變得非常簡單。
- 網頁開發:Django 和 Flask 是兩個受歡迎的框架,用於構建強大的網頁應用。
- 爬蟲:Python 擁有許多專門用於網路爬蟲的庫,如 BeautifulSoup 和 Scrapy,能夠快速構建網頁抓取程序,適合數據收集和分析。
- 多用途:Python適用於數據分析、機器學習、網頁開發、自動化腳本等多種應用場景。
- 數據分析:Python在數據科學領域非常流行,提供了強大的數據處理和分析工具。
- 機器學習:使用像 scikit-learn 和 TensorFlow 這樣的庫來構建和訓練機器學習模型。
### 安裝Python
- VSCode
<!-- - Window -->
[Visual Studio Code 撰寫 Python 程式](https://hackmd.io/@smallshawn95/vscode_write_py)
<!--
- MacOS
- 下載 VSCode
1. 到 [VSCode 官網](https://code.visualstudio.com/)
2. 點擊下載 VSCode
3. 下載後開啟 VSCode
4. 在 VSCode 中點擊「延伸模組」
5. 搜尋「Python」點擊下載
6. 搜尋「Code Runner」
- 下載 Python
1. 到 [Python 官網](https://www.python.org/)
2. 下載任意版本(3.12)
3.
-->
- online (Google Colab)
1. 開啟 [Python 入門 Google Colab 教材](https://colab.research.google.com/drive/1kS8MKXbLGnzgibJCmjTgn1rt8A-wyUhq?usp=sharing)
2. 直接執行就好
### 第一個Python程序
- **顯示 `Hello, World!`**
1. 打開你電腦上的Python編輯器。
2. 在編輯器中輸入以下代碼:
```python
print("Hello, World!")
```
3. 直接運行程序,你應該會看到輸出:
```
Hello, World!
```
### `print` 函式
- **介紹**
- `print` 函式是 Python 中最常用的輸出函式,用於將信息輸出到控制台或終端。它可以打印字符串、數字、變量的值以及其他對象。
- **基本用法**
- **打印字符串**:直接在 `print` 函式中輸入字符串。
```python
print("Hello, World!") # 輸出: Hello, World!
```
- **打印數字**:可以直接打印數字。
```python
print(123) # 輸出: 123
```
- **打印變量**:將變量的值打印出來。
```python
name = "Alice"
age = 25
print(name) # 輸出: Alice
print(age) # 輸出: 25
```
- **同時打印多個值**:可以用逗號分隔多個值,`print` 函式會將它們打印在一起,用空格分隔。
```python
print("Name:", name, "Age:", age) # 輸出: Name: Alice Age: 25
```
- **控制行結尾**
- **默認換行**:`print` 函式默認在輸出後換行。
```python
print("Hello")
print("World")
# 輸出:
# Hello
# World
```
- **不換行**:可以通過 `end` 參數設置輸出後不換行。
```python
print("Hello", end="")
print("World")
# 輸出: HelloWorld
```
- **自定義結尾字符**:可以設置自定義的結尾字符。
```python
print("Hello", end=", ")
print("World")
# 輸出: Hello, World
```
作業解答:顯示自己的名字、學號、系級
```python=
print("史伯勳")
print("411285049")
print("資工二")
```
### 輸入
在 Python 中,input() 是一個很常用的函式,用來讓使用者輸入。當程序執行到 input() 時,它會暫停並等待用戶輸入內容,直到用戶按下 Enter 鍵。
##### `input()` 函式的基本使用
```python=
input()
```
##### 印出輸入
```python=
print(input("輸入:")) #在 input 的括號中,可以放入提示字,在 input 前輸出
```
##### 最常使用:使用變數輸入輸出
```python=
name = input("輸入名字:")
print(name)
```
## 第二章:基本語法
### 數據類型和變數
* #### 數據類型(數字、字串、布林)
#### 1. 數字
- **整數 (Integer)**:沒有小數部分的數字,例如:5, -3, 42。
- **浮點數 (Float)**:有小數部分的數字,例如:3.14, -0.001, 2.0。
##### 例子
```python=
x = 5 # 整數
y = 3.14 # 浮點數
print(x) # 輸出: 5
print(y) # 輸出: 3.14
```
#### 2. 字串 (String)
- 字串是一串字符,用於表示文本。
- 可以使用單引號 ' 或雙引號 " 定義字符串。
##### 例子
```python=
name = "Alice"
greeting = 'Hello, World!'
print(name) # 輸出: Alice
print(greeting) # 輸出: Hello, World!
```
#### 3. 布林值 (Boolean)
- 布林值只有兩個取值:True 和 False。
- 常用於條件判斷。
##### 例子
```python=
is_student = True
is_teacher = False
print(is_student) # 輸出: True
print(is_teacher) # 輸出: False
```
---
* #### 變數
- 變數是用來存儲數據的容器,可以用來保存各種類型的數據。
- 在Python中,變數是動態類型的,不需要事先聲明類型。
#### 如何定義變數
- 只需要使用 `=` 將一個值給一個變數。
#### 例子
```python=
# 定義變數
x = 5 # 整數 int
y = 3.14 # 浮點數(有小數點) float
name = "Alice" # 字串 str
is_student = True # 布林值 bool
# 輸出變數的值
print(x) # 輸出: 5
print(y) # 輸出: 3.14
print(name) # 輸出: Alice
print(is_student) # 輸出: True
```
> #### 注意
> * 變數名必須以字母或下劃線 _ 開頭,不能以數字開頭。
> * 變數名區分大小寫(name 和 Name 是不同的變數)。
> * 使用有意義的變數名,以提高代碼的可讀性。
作業:定義你的名字和學號,輸出~
```python=
name = "王小明"
studentNumber = "4100000000"
print(name)
print(studentNumber)
```
作業2:顯示學號、系級以及姓名的輸入格,並輸出
```python=
name = input("請輸入名字:")
studentNumber = input("輸入學號:")
department = input("輸入系及")
print(name)
print(studentNumber)
print(department)
```
---
### 運算符
- 基本算術運算符
- **加法 (+)**:將兩個數字相加。
- **減法 (-)**:將一個數字從另一個數字中減去。
- **乘法 (*)**:將兩個數字相乘。
- **除法 (/)**:將一個數字除以另一個數字,結果為浮點數。
```python=
a = 5
b = 3
result = a + b # result 為 8
result = a - b # result 為 2
result = a * b # result 為 15
result = a / b # result 為 1.6667
```
- **整數除法 (//)**:將一個數字除以另一個數字,結果為整數。
- **取餘 (%)**:計算除法的餘數。
- **指數 ```(**)```**:計算數字的冪。
```python=
a = 5
b = 3
result = a // b # result 為 1 (5 / 3 = 1...2)
result = a % b # result 為 2 (5 / 3 = 1...2)
result = a ** b # result 為 125 (5 x 5 x 5 = 125)
```
作業:定義並顯示 result
```python=
result = 5*4
print("5 x 4 =", result)
result = 5%3
print("5 / 3 = 1 ...", result)
```
- 比較運算符
- **大於 (>)**:檢查一個值是否大於另一個值。
- **小於 (<)**:檢查一個值是否小於另一個值。
```python=
a = 5
b = 3
a > b # 結果為 True
a < b # 結果為 False
```
- **等於 (==)**:檢查兩個值是否相等。
- **不等於 (!=)**:檢查兩個值是否不相等。
- **大於等於 (>=)**:檢查一個值是否大於或等於另一個值。
- **小於等於 (<=)**:檢查一個值是否小於或等於另一個值。
```python=
a = 5
b = 3
a == b # 結果為 False
a != b # 結果為 True
a >= b # 結果為 True
a <= b # 結果為 False
```
作業:輸入兩個成績,比較是否相等,回傳 True 或是 False
```python=
John_Math = 84
Max_Math = 94
print(John_Math == Max_Math)
```
- 邏輯運算符
- 和 (and):當兩個條件都為 True 時,結果為 True。
- 或 (or):當至少一個條件為 True 時,結果為 True。
- 非 (not):將布林值取反。
```python=
x = True
y = False
result = x and y # 結果為 False
result = x or y # 結果為 True
result = not x # 結果為 False
```
這些運算符是進行各種數學運算和邏輯判斷的基本工具。掌握它們可以幫助你進行更複雜的計算和條件判斷。
#### 進階
* 運用**運算符**定義變數
```python=
a = 1
b = 2
c = a + b # c = 1 + 2
d = a > b # 1 > 2 => d = false
```
* 額外:**邏輯運算符**定義變數
* 邏輯運算符 or
* c = a or b:
* or 運算符會返回第一個布爾值為 True 的操作數。如果 a 是 True(非零數值被視為 True),則返回 a 的值,否則返回 b 的值。
* 由於 a 的值是 1(True),所以 c 被賦值為 a 的值,即 1。
* d = b or a:
* 這裡 b 的值是 2(True),所以 d 被賦值為 b 的值,即 2。
* 邏輯運算符 and
* e = a and b:
* and 運算符會返回第一個布爾值為 False 的操作數,如果所有操作數都是 True,則返回最後一個操作數。
* 由於 a 和 b 都是 True,所以 e 被賦值為 b 的值,即 2。
* f = b and a:
* 這裡 b 的值是 2(True),a 的值是 1(True)。因此,f 被賦值為 a 的值,即 1。
```python=
a = 1
b = 2
c = a or b # 因為 a 是 True,所以返回 a 的值
d = b or a # 因為 b 是 True,所以返回 b 的值
e = a and b # 因為 a 和 b 都是 True,所以返回 b 的值
f = b and a # 因為 b 和 a 都是 True,所以返回 a 的值
```
作業:輸入國文成績以及英文成績是否通過
```python=
chinese = input()#輸入國文成績
english = input()#輸入英文成績
passChinese = chinese >= 60
passEnglish = chinese >= 60
# 顯示是否及格
print(passChinese)
print(passEnglish)
passBoth = passChinese and passEnglish# 兩個科目都過
passOne = passChinese or passEnglish# 至少一個科目過
# 顯示結果
print(passBoth)
print(passOne)
```
---
### 字串操作
#### 字串拼接
- **使用 `+` 拼接字串**:將多個字串連接在一起。
```python=
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # 輸出: John Doe
```
作業:打招呼
```python=
message = "Hello"
name = "John"
greeting = message + ", " + name
print(greeting)
```
#### 字串使用
- **`len()`**:返回字符串的長度。
```python=
text = "Hello, world!"
print(len(text)) # 輸出: 13
```
- **`upper()`**:將字符串轉換為全大寫。
```python=
text = "hello"
print(text.upper()) # 輸出: HELLO
```
- **`lower()`**:將字符串轉換為全小寫。
```python=
text = "HELLO"
print(text.lower()) # 輸出: hello
```
- **`strip()`**:移除字符串開頭和結尾的空白字符。
```python=
text = " Hello, world! "
print(text.strip()) # 輸出: Hello, world!
```
- **`replace()`**:將字符串中的某個子字符串替換為另一個子字符串。
```python=
text = "Hello, world!"
print(text.replace("world", "Python")) # 輸出: Hello, Python!
```
- **`find()`**:返回子字符串在字符串中的起始位置,如果沒有找到則返回 -1。
```python=
text = "Hello, world!"
position = text.find("world")
print(position) # 輸出: 7
```
## 第三章:控制流程工具
### 條件語句
* #### if 判斷
if 語句用於根據條件執行不同的代碼塊。基本語法如下:
```python=
# condition 和 another_condition 視為 bool
if condition:
# 當 condition 為真時執行這段代碼
elif another_condition:
# 當 another_condition 為真時執行這段代碼
else:
# 當所有條件都不滿足時執行這段代碼
```
```python=
a = 10
b = 5
if b > a:
print("b 大於 a")
elif a > b:
print("a 大於 b")
else:
print("a 等於 b")
```
作業:判斷是否及格
```python=
Chinese = input()
English = input()
if Chinese >= 60 and English >= 60 :
print("及格")
elif Chinese >= 60 :
print("只有中文及格")
elif English >= 60 :
print("只有英文及格")
else:
print("不及格")
```
作業2:輸入出生年份,判斷是否大於18歲
```python=
bornYear = input("輸入出生年份(西元):")
age = 2024 - int(bornYear)
if age > 18:
print("大於 18 歲")
elif age == 18:
print("剛好 18 歲")
else:
print("小於 18 歲")
```
---
### 循環
* #### for 循環
for 循環用於遍歷一個序列(如列表、元組或字串)。基本語法如下:
```python=
for item in sequence:
# 對於 sequence 中的每個 item 執行這段代碼
```
用數字範圍
```python=
for i in range(10):
print(i) #依序輸出 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
```
作業:輸出 5 x 1 ~ 5 x 9
```python=
for i in range(1, 10):
print("5 x ", i, " =", 5*i)
```
* #### while 循環
while 循環在條件為真時重複執行一段代碼。基本語法如下:
```python=
while condition:
# 當 condition 為真時執行這段代碼
```
```python=
a = 10
b = 5
while a > b: # a > b 不成立時跳出,會在 a == b 時跳出
b = b + 1
print(b) # b = 10
```
作業:輸入成績,直到成績大於 60 時,輸出“及格了”並跳出迴圈
```python=
while True:
score = int(input("輸入成績:"))
if score >= 60:
print("及格了")
break
```
作業2:輸入成績,直到成績大於 60 的次數大於三次,輸出“及格三次”並跳出迴圈
```python=
passTime = 0
while True:
score = int(input("輸入成績:"))
if score >= 60:
passTime +=1
if passTime == 3:
print("及格三次")
break
```
## 第一堂實作
做出一個 BMI 計算機,可以輸入身高、體重,計算出 BMI 以及建議方向。
```python=
while True:
height = input("請輸入身高(cm): ")
weight = input("請輸入體重(kg): ")
height = float(height)
weight = float(weight)
height = height / 100
bmi = weight / height ** 2
print(bmi)
if bmi < 18.5:
print("過輕")
elif bmi < 24:
print("正常")
elif bmi < 27:
print("過重")
else:
print("肥胖")
message = input("是否繼續計算?(不繼續請輸入「n」")
if message == "n":
break
```
進階:
1. 判斷輸入是否合理(體重小於零、身高小於零之類的)
2. 輸入結束後,可輸入 Y 或是 N,決定是否繼續執行計算機
```python=
print("歡迎來到 BMI 計算器!")
print("BMI(Body Mass Index)是身體質量指數,用於評估健康狀況。")
while True:
height = input("請輸入身高(cm): ")
weight = input("請輸入體重(kg): ")
height = float(height)
weight = float(weight)
# 計算 BMI
height = height / 100 # 轉換為公尺
bmi = weight / (height ** 2)
print(f"\n您的 BMI 值為: {bmi:.2f}")
# 判斷健康狀況
if bmi < 18.5:
print("您的體重過輕,建議增加體重。")
elif bmi < 24:
print("您的體重正常,保持健康!")
elif bmi < 27:
print("您的體重略為過重,注意飲食和運動。")
elif bmi < 30:
print("您的體重過重,建議進行減重。")
else:
print("您的體重屬於肥胖範圍,建議諮詢專業醫師。")
# 詢問是否繼續
message = input("\n是否繼續計算 BMI?(輸入「n」退出,或按其他鍵繼續): ")
if message.lower() == "n":
print("感謝您使用 BMI 計算器,再見!")
break
else:
print("\n-----------------------------------")
```
進階:九九乘法表
```python=
for i in range (1, 10):
for j in range (1, 10):
print(i, "x", j, "=", i * j, end = ", ")
print("\n")
```
## 第四章:數據結構
### 列表 (List)
- **創建和使用列表**
- **列表的特色**
- **有序性**:列表中的元素是有序的,並且可以通過索引訪問。
- **可變性**:列表中的元素可以被修改、添加或刪除。
- **異構性**:列表可以包含不同類型的元素,例如數字、字符串、列表等。
- **動態長度**:列表的大小是可變的,可以根據需要動態調整。
- **用途**
- **存儲多個相關的值**:列表可以用來存儲多個相關的數據,例如一組學生的姓名、一組數字等。
- **數據操作和處理**:列表提供了許多方便的操作方法,可以輕鬆地進行數據的添加、刪除、排序等操作。
- **迭代和循環**:列表可以與 `for` 循環一起使用,用於遍歷所有元素。
- **創建列表**:可以使用方括號 `[]` 創建列表。列表可以包含任何類型的元素,如數字、字符串、甚至是其他列表。
```python
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "apple", 3.14, True]
```
- **訪問元素**:通過索引訪問列表中的元素,索引從 0 開始。
```python
print(fruits[0]) # 輸出: apple
print(numbers[2]) # 輸出: 3
```
- **修改元素**:可以通過索引直接修改列表中的元素。
```python
fruits[1] = "blueberry"
print(fruits) # 輸出: ['apple', 'blueberry', 'cherry']
```
- **添加元素**:使用 `append()` 方法將元素添加到列表末尾。
```python
fruits.append("orange")
print(fruits) # 輸出: ['apple', 'blueberry', 'cherry', 'orange']
```
- **刪除元素**:使用 `remove()` 方法刪除指定的元素,或使用 `pop()` 方法刪除指定索引處的元素。
```python
fruits.remove("blueberry")
print(fruits) # 輸出: ['apple', 'cherry', 'orange']
fruits.pop(1)
print(fruits) # 輸出: ['apple', 'orange']
```
- **列表長度**:使用 `len()` 函式獲取列表的長度。
```python
print(len(fruits)) # 輸出: 2
```
---
### 元組 (Tuple)(不可變的 List )
- **創建和使用元組**
- **元組的特色**
- **有序性**:元組中的元素是有序的,並且可以通過索引訪問。
- **不可變性**:元組中的元素一旦創建就不能修改、添加或刪除。
- **異構性**:元組可以包含不同類型的元素,例如數字、字符串、列表等。
- **高效性**:由於不可變,元組的操作速度通常比列表更快。
- **用途**
- **存儲固定數據**:元組適用於存儲不需要修改的一組數據,例如坐標、顏色值等。
- **作為字典鍵**:元組可以作為字典的鍵,而列表不行,因為元組是不可變的。
- **數據完整性**:使用元組可以保證數據的完整性,避免意外修改。
- **創建元組**:可以使用逗號分隔元素或使用小括號 () 創建元組。
```python
coordinates = 10, 20
person = ("John", 30, "Engineer")
```
- **訪問元素**:通過索引訪問元組中的元素,索引從 0 開始。
```python
print(coordinates[0]) # 輸出: 10
print(person[2]) # 輸出: Engineer
```
- **不可變性**:元組中的元素是不可變的,不能修改。
```python
coordinates[0] = 15 # 會引發錯誤
```
---
### 集合 (Set)(不重複的 List ; List 的種類)
- **創建和使用集合**
- **集合的特色**
- **無序性**:集合中的元素是無序的,不能通過索引訪問。
- **唯一性**:集合中的元素是唯一的,重複的元素會被自動去重。
- **可變性**:集合本身是可變的,可以添加或刪除元素,但集合中的元素必須是不可變的。
- **用途**
- **去除重復**:可以用集合來去除列表中的重複元素。
- **集合操作**:可以進行集合的交集、並集和差集操作。
- **檢查成員**:可以快速檢查一個元素是否在集合中。
- **創建集合**:可以使用大括號 `{}` 創建集合。
```python
fruits_set = {"apple", "banana", "cherry"}
numbers_set = {1, 2, 3, 4, 5}
```
- **添加元素**:使用 `add()` 方法添加元素到集合。
```python
fruits_set.add("orange")
print(fruits_set) # 輸出: {'apple', 'banana', 'cherry', 'orange'}
```
- **刪除元素**:使用 `remove()` 方法刪除指定元素。
```python
fruits_set.remove("banana")
print(fruits_set) # 輸出: {'apple', 'cherry', 'orange'}
```
- **集合操作**:
- **交集**:使用 `&` 或 `intersection()` 方法。
```python
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b) # 輸出: {3}
```
- **聯集**:使用 `|` 或 `union()` 方法。
```python
print(a | b) # 輸出: {1, 2, 3, 4, 5}
```
- **差集**:使用 `-` 或 `difference()` 方法。
```python
print(a - b) # 輸出: {1, 2}
```
---
### 字典 (Dictionary)(有標題的 List )
- **創建和使用字典**
- **字典的特色**
- **鍵值對**:字典是由鍵值(key, value)對組成的,每個鍵對應一個值。
- **無序性**:在 Python 3.7 之前,字典是無序的;從 Python 3.7 開始,字典保留插入順序。
- **可變性**:字典是可變的,可以修改、添加或刪除鍵值對。
- **用途**
- **存儲映射關係**:適合用來存儲數據之間的映射關係,例如用戶信息、配置參數等。
- **高效查找**:可以快速查找、插入和刪除數據。
- **結構化數據**:可以用來存儲結構化數據,例如 JSON 對象。
- **創建字典**:可以使用大括號 `{}` 創建字典。
```python
country2Continent = {'Taiwan': 'Asia', 'USA': 'North America', 'Germany': 'Europe', 'Kenya': 'Africa', '阿拉伯聯合大公國' : '亞洲'}
```
- **訪問元素**:通過鍵訪問字典中的值。
```python
print(country2Continent['Taiwan'])
print(country2Continent['Germany'])
print(country2Continent['阿拉伯聯合大公國'])
```
- **添加或修改元素**:直接通過鍵賦值。
```python
country2Continent['阿拉伯聯合大公國'] = 'Asia'
country2Continent['Turkey'] = 'Asia'
print(country2Continent)
```
- **刪除元素**:使用 `del` 關鍵字刪除指定鍵值對。
```python
del country2Continent['Turkey']
print(country2Continent)
country2Continent['Türkiye'] = 'Asia'
print(country2Continent)
```
- **遍歷字典**
- **常見需求**
1. **只列鍵**
2. **只列值**
3. **同時拿到鍵和值**
4. **需要索引/排序時的遍歷**
```python
# 1. 遍歷鍵(預設行為)
for country in country2Continent: # 同 for country in country2Continent.keys()
print(country)
# 2. 遍歷值
for continent in country2Continent.values():
print(continent)
# 3. 同時遍歷鍵和值
for country, continent in country2Continent.items():
print(f"{country} ➜ {continent}")
# 4. 需要索引時
for idx, (country, continent) in enumerate(country2Continent.items(), start=1):
print(f"{idx}. {country} 位於 {continent}")
# 5. 依字母排序後再遍歷
for country in sorted(country2Continent):
print(country, country2Continent[country])
```
## 第五章:函式
### **基本函式定義和調用**
- **定義函式**:使用 `def` 關鍵字定義函式。
```python
def greet(name):
return f"Hello, {name}!" # f 是因為會回傳變數
```
- **調用函式**:通過函式名和參數調用函式。
```python
print(greet("Alice")) # 輸出: Hello, Alice!
```
- **默認參數值**:可以為參數設置默認值。
```python
def greet(name="World"):
return f"Hello, {name}!"
print(greet()) # 輸出: Hello, World!
print(greet("Bob")) # 輸出: Hello, Bob!
```
- **返回值**:函式可以返回一個值,使用 `return` 關鍵字。
```python
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 輸出: 8
```
- **變數範圍**
- 區分:Python 中變數可分為「全域變數(global)」與「區域變數(local)」。
- 區域變數:在函式內部定義,僅在該函式中有效。
```python=
def my_func():
x = 10 # x 是區域變數
print(x)
my_func()
print(x) # 會錯誤:x is not defined
```
- 全域變數:在函式外部定義,可以在多個函式中被讀取(但要修改必須使用 global)。
```python=
def my_func():
global x # x 改為全域變數
x = 10
print(x)
my_func()
print(x) # 可以正常顯示 x
```
作業:寫一個函式判斷是不是質數
```python=
def isPrime(n):
for i in range(2, n//2):
if n % i == 0:
return False
return True
print(isPrime(13))
print(isPrime(15))
```
## 第六章:模組與套件
### 模組
- **介紹**
- 模組 指的是一個包含 Python 代碼的文件,可以被其他 Python 程序導入和使用。模組讓我們可以把代碼拆分成更小、更易管理的部分,提高代碼的可讀性和重用性。
- Python 有兩種類型的模組:
- **內建模組**:Python 自帶的模組,比如 `math`、`os` 等,這些模組可以直接導入使用。
- **自定義模組**:由開發者自己編寫的模組,通常是包含在一個 `.py` 文件中的代碼。
- **導入和使用內建模組**
- **導入模組**:使用 `import` 來導入模組。導入後,可以通過模組名來使用模組內的函式和變量。
```python
import math # 導入內建的數學模組
# 使用 math 模組中的 sqrt() 函式來計算平方根
result = math.sqrt(16)
print(result) # 輸出: 4.0
```
- **導入模組中的特定功能**:有時我們只需要模組中的某個函式或變量,可以使用 `from ... import ...` 語句來導入特定的部分。
```python
from math import pi # 只導入 math 模組中的 pi 常量
print(pi) # 輸出: 3.141592653589793
```
- **使用別名**:如果模組名稱太長或者與現有的變量名衝突,可以使用 `as` 為模組或函式設置別名。
```python
import math as m # 將 math 模組重命名為 m
print(m.sqrt(25)) # 輸出: 5.0
```
- **自定義模組**
- **創建自定義模組**:將一些功能寫入一個 `.py` 文件中,即可將其視為一個模組。然後可以在其他文件中導入這個模組。
```python
# mymodule.py 文件
def greet(name):
return f"Hello, {name}!"
```
- **導入自定義模組**:使用 `import` 導入自定義模組後,可以使用模組中的函式或變量。
```python
# 在其他文件中使用自定義模組
import mymodule
message = mymodule.greet("Alice")
print(message) # 輸出: Hello, Alice!
```
<!--
## 第八章:簡單數據分析
[數據分析入門](https://intl.finebi.com/zh-TW/blog/excel-data-analysis)
[Python 從入門到數據分析](https://medium.com/finformation%E7%95%B6%E7%A8%8B%E5%BC%8F%E9%81%87%E4%B8%8A%E8%B2%A1%E5%8B%99%E9%87%91%E8%9E%8D/python-%E5%BE%9E%E5%85%A5%E9%96%80%E5%88%B0%E6%95%B8%E6%93%9A%E5%88%86%E6%9E%90-%E7%AC%AC%E4%B8%80%E8%AC%9B-python-%E7%B0%A1%E4%BB%8B-python%E4%BB%8B%E7%B4%B9%E8%88%87%E5%88%9D%E6%8E%A2-958e909f49f8)
[【Python實作】生活中的資料科學,用模型挑出高C/P智慧型手機](https://medium.com/finformation%E7%95%B6%E7%A8%8B%E5%BC%8F%E9%81%87%E4%B8%8A%E8%B2%A1%E5%8B%99%E9%87%91%E8%9E%8D/python%E5%AF%A6%E4%BD%9C-%E7%94%9F%E6%B4%BB%E4%B8%AD%E7%9A%84%E8%B3%87%E6%96%99%E7%A7%91%E5%AD%B8-%E7%94%A8%E6%A8%A1%E5%9E%8B%E6%8C%91%E5%87%BA%E9%AB%98c-p%E6%99%BA%E6%85%A7%E5%9E%8B%E6%89%8B%E6%A9%9F-99752d3c7f0d)
[【Python實作】Back to E’shanzen資料科學的商業分析](https://medium.com/finformation%E7%95%B6%E7%A8%8B%E5%BC%8F%E9%81%87%E4%B8%8A%E8%B2%A1%E5%8B%99%E9%87%91%E8%9E%8D/case-back-to-eshanzen%E8%B3%87%E6%96%99%E7%A7%91%E5%AD%B8%E7%9A%84%E5%95%86%E6%A5%AD%E5%88%86%E6%9E%90-9fccd99cb38b)
[利用集群分析掌握消費者輪廓,Python實作(一)](https://medium.com/finformation%E7%95%B6%E7%A8%8B%E5%BC%8F%E9%81%87%E4%B8%8A%E8%B2%A1%E5%8B%99%E9%87%91%E8%9E%8D/%E5%88%A9%E7%94%A8%E9%9B%86%E7%BE%A4%E5%88%86%E6%9E%90%E6%8E%8C%E6%8F%A1%E6%B6%88%E8%B2%BB%E8%80%85%E8%BC%AA%E5%BB%93-python%E5%AF%A6%E4%BD%9C-%E4%B8%80-7086082fbb2e)
### 使用pandas
- 基本數據操作
### 使用numpy
- 基本數值計算
-->
## 結語
### 推薦資源
[Python 教學-STEAM 教育學習網](https://steam.oxxostudio.tw/category/python/info/start.html)
[Python 3 教程-runoob](https://www.runoob.com/python3/python3-tutorial.html)
[Python 3 語法大全-HackMD](https://hackmd.io/@BlueLancaster/Python#%E8%AE%8A%E6%95%B8%E5%8F%8A%E5%9E%8B%E6%85%8B%E8%BD%89%E6%8F%9B)
[Python基本語法-HackMD](https://hackmd.io/@yizhewang/Sk_yOs-zm?type=view#%E8%B3%87%E6%96%99%E5%9E%8B%E6%85%8B)