適合程式設計入門、IoT 控制、資料處理與自動化腳本課程的 Python 基礎教材。
重點是讓學生能快速理解語法、能自己撰寫程式、能讀懂錯誤訊息並除錯。
python3 --version
python3
python3 hello.py
nano hello.py
print("Hello Python")
python3 hello.py
print("Hello World")
print("歡迎學習 Python")
# 這是一行註解
print("test")
message = """這是一段
多行文字
可用來做說明"""
print(message)
name = "Alice"
age = 20
height = 165.5
is_student = True
| 型態 | 範例 | 說明 |
|---|---|---|
| str | "hello" | 字串 |
| int | 123 | 整數 |
| float | 3.14 | 浮點數 |
| bool | True, False | 布林值 |
| list | [1, 2, 3] | 串列 |
| dict | {"a":1} | 字典 |
x = 123
print(type(x))
name = input("請輸入姓名: ")
print("你好,", name)
age = int(input("請輸入年齡: "))
print(age + 1)
a = int("123")
b = float("3.14")
c = str(100)
| 類型 | 符號 | 範例 |
|---|---|---|
| 加減乘除 | + - * / | 3 + 2 |
| 整除 | // | 7 // 2 |
| 餘數 | % | 7 % 2 |
| 次方 | ** | 2 ** 3 |
| 比較 | == != > < >= <= | x == 10 |
| 邏輯 | and or not | x > 0 and x < 10 |
score = int(input("請輸入分數: "))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
for i in range(10):
if i == 5:
break
print(i)
for i in range(5):
if i == 2:
continue
print(i)
text = "Python"
print(text[0])
print(len(text))
print(text.lower())
print(text.upper())
name = "Tom"
age = 20
print(f"我的名字是 {name}, 年齡是 {age}")
fruits = ["apple", "banana", "orange"]
print(fruits[0])
fruits.append("grape")
print(fruits)
print(len(fruits))
for fruit in fruits:
print(fruit)
append() 新增元素remove() 移除元素sort() 排序len() 長度student = {
"name": "Alice",
"age": 20,
"major": "EE"
}
print(student["name"])
print(student["age"])
student["grade"] = "A"
print(student)
for key, value in student.items():
print(key, value)
def hello(name):
print("Hello", name)
hello("Richard")
def add(a, b):
return a + b
result = add(3, 5)
print(result)
def greet(name="student"):
print("Hello", name)
greet()
greet("Tom")
import math
print(math.sqrt(16))
import random
print(random.randint(1, 10))
from datetime import datetime
print(datetime.now())
with open("test.txt", "w", encoding="utf-8") as f:
f.write("Hello Python")
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
with open(...),因為這是較安全且標準的寫法。try:
num = int(input("請輸入整數: "))
print(10 / num)
except ValueError:
print("輸入的不是整數")
except ZeroDivisionError:
print("不能除以 0")
| 指令 | 用途 |
|---|---|
python3 -m pip install 套件名 | 安裝套件 |
python3 -m pip uninstall 套件名 | 移除套件 |
python3 -m pip list | 查看已安裝套件 |
python3 -m pip show 套件名 | 查看套件資訊 |
python3 -m pip install -U 套件名 | 更新套件 |
python3 -m pip install requests
python3 -m pip list
如果課程稍微進階,建議讓學生知道虛擬環境的概念。
python3 -m venv myenv
source myenv/bin/activate
python3 -m pip install requests
離開虛擬環境:
deactivate
| 錯誤 | 原因 | 建議 |
|---|---|---|
| IndentationError | 縮排錯誤 | 確認空白數量一致 |
| NameError | 變數名稱錯誤或未定義 | 檢查拼字 |
| TypeError | 型態不符 | 確認資料型別 |
| ValueError | 轉型失敗 | 確認輸入內容格式 |
| ModuleNotFoundError | 模組未安裝 | 用 pip 安裝 |
只要把這些基礎語法打穩,學生就能很快接上資料處理、感測器控制、網路通訊與自動化應用。Python 最重要的不是背語法,而是理解程式如何一步一步解決問題。