8 頁掌握 Python 核心語法:語法簡單、功能強大,從簡單運算到 AI 系統都能處理。
接近自然語言,好讀好寫
彈性處理各類問題
變數到類別一次看完
# 輸出訊息到畫面 print("Xin chào tất cả mọi người") # 安裝外部套件(在 Terminal) pip install requests
age_1 對,1st_age 錯my_age 或 myAgeage 與 Age 是兩個變數/ 一律得 float;// 取整數商;round() 四捨五入| 型態 | 說明 | 範例 |
|---|---|---|
int | 整數 | 26 |
float | 小數 | 22.5 |
str | 字串 | "Minh" |
name = "Minh" age = 18 print(type(age)) # <class 'int'> print(16000 // 30) # 533 print(f"{name}, {age} 歲") year = int(input("出生年:"))
input() 取得的資料一律是字串,運算前要用 int() 或 float() 轉型。True、False,not 可反轉> < == !=;單個 = 是賦值and 全部為真才為真;or 有一個為真即為真IndentationError.upper() 統一大小寫,避免 'a' 與 'A' 判斷失準choice = input("A: 牛排 / B: 豬排:").upper()
if choice == "A":
print("牛排 500k")
elif choice == "B":
print("豬排 450k")
else:
print("選擇無效!")
-1 是最後一個[start:end] 不含 end;字串同樣適用append/extend;刪除 remove/popin、index()、len()| List [ ] | Tuple ( ) | |
|---|---|---|
| 修改 | 可新增、修改、刪除 | 不可變 |
| 強行修改 | 成功 | TypeError |
s = ["Minh", "Hoa", "Kiệt", "Linh"] print(s[0], s[-1]) # Minh Linh print(s[1:3]) # ['Hoa', 'Kiệt'] s.append("An") s.pop(0) print("Hoa" in s) # True "/".join(["01", "05"]) # '01/05' "01/05".split("/") # ['01', '05']
for 逐一走訪清單或字串,可巢狀組合break 結束整個迴圈;continue 跳過本輪+=、累乘 *=;abs() 取絕對值range(start, stop, step) 產生數字序列while True 必須搭配 if ... break,或在條件中更新計數器。for item in ["麵包", "三明治", "漢堡"]:
if item == "三明治":
continue
print(item)
for n in range(5, 10, 2):
print(n) # 5 7 9
count = 1
while count <= 5:
count += 1
def 定義後要呼叫才會執行name=值 不受順序限制return 回傳並立即結束函式;沒寫則得 None;多值回傳為 Tuple| 變數 | 位置 | 範圍 |
|---|---|---|
| 區域 | 函式內 | 僅函式內 |
| 全域 | 函式外 | 整個檔案 |
def calc_total(price, shipping=50):
return price + shipping
print(calc_total(1000)) # 1050
print(calc_total(1000, shipping=80)) # 1080
def divide(a, b):
return a // b, a % b # Tuple
# 函式內升級為全域變數
global total
{}:Key 唯一,Value 可為任何型態d[key] 找不到會報錯,d.get(key, 提示) 較安全keys()、values()、items()import x、import x as y、from x import frandom、string、requests(呼叫 API)__init__ 初始化,self 代表自己,class B(A) 繼承phone = {"品牌": "Apple", "型號": "iPhone 14"}
for k, v in phone.items():
print(f"{k}: {v}")
class Character:
def __init__(self, name):
self.name = name
self.hp = 500
class Warrior(Character):
def attack(self):
print(f"{self.name} 發動攻擊!")
Warrior("Knight").attack()