第一個月 · Python 入門 Month 1 · Python Fundamentals

Lesson 01–06 完整學習筆記 Lesson 01–06 Complete Study Notes

涵蓋 Python 基礎核心概念,以 HR 實際應用場景貫穿,方便日後快速溫習。 Covers core Python fundamentals with HR workplace scenarios throughout, designed for quick revision.

Python 程式學習與 HR 應用的抽象插圖
6
課堂
Lessons
10+
核心概念
Key Concepts
6
練習完成
Exercises Done
1
HR 自動化工具
HR Tool Built
📋 課堂目錄 📋 Table of Contents
Lesson 01
輸出、變數與 f-string Output, Variables & f-string
讓電腦說話、記住資料,並格式化輸出 Make the computer speak, remember data, and format output
print() — 讓電腦輸出文字 print() — Display text on screen
print("你好,我是 Python!Hello, I am Python!")
print("我在學習 AI 技能。I am learning AI skills.")
變數 — 讓電腦記住資料 Variables — Store data in memory

用 = 把資料「裝入」變數。文字用 " " 包住,數字不需要。 Use = to assign data to a variable. Text needs " " quotes; numbers do not.

employee_name = "James Tong"    # 文字(str)Text (str)
department     = "人力資源部HR Department"
years          = 3               # 整數(int)Integer (int)
salary         = 25000.50        # 浮點數(float)Decimal (float)
f-string — 把變數嵌入句子 f-string — Embed variables inside text

在引號前加 f,用 { } 包住變數名稱。 Add f before the quote, then wrap variable names in { }.

name = "James Tong"
dept = "人力資源部HR Department"
print(f"員工 Employee {name} 所屬部門: — Department: {dept}")
# 輸出:員工 James Tong 所屬部門:人力資源部Output: Employee James Tong — Department: HR Department
資料類型
Data Types
str 文字Text、int 整數Integer、float 小數Decimal
輸出指令
Output
print()
嵌入語法
Embed Syntax
f"...{variable}..."
Lesson 02
使用者輸入 input() User Input with input()
讓程式暫停,等待使用者輸入資料 Pause the program and wait for the user to type something
input() 基本用法 Basic Usage of input()
name = input("請輸入你的名字:Enter your name: ")
dept = input("請輸入你的部門:Enter your department: ")
print(f"你好,Hello, {name}! 你所在的部門是 Your department is {dept}.")
⚠️
重要:input() 收到的任何東西都是文字(str),即使你輸入數字 1,Python 收到的也是 "1"。需要做數學運算時,必須先用 int() 或 float() 轉換。 Important: input() always returns a string (str). Even if you type 1, Python receives "1". You must convert it with int() or float() before doing any math.
Lesson 03
條件判斷 if / else Conditionals if / else
滿足條件時做 A,否則做 B;以及 int() vs float() Do A when condition is met, otherwise do B; plus int() vs float()
if / else 結構 if / else Structure

冒號 : 後面的程式碼必須縮排(Tab 鍵)。 Code after the colon : must be indented (press Tab).

months = float(input("請輸入入職月數:Enter months of service: "))

if months < 3:
    print("仍在試用期Still on probation")
else:
    print("已過試用期Probation completed")
int() vs float() — 數字類型轉換 int() vs float() — Number Type Conversion
函式Function 接受Accepts 例子Example 不能處理Cannot Handle
int()整數字串Whole number stringsint("3") → 3"0.5" ← 會報錯Error!
float()整數或小數Whole or decimalfloat("0.5") → 0.5—
💡
處理年資時,優先用 float(),因為員工可能填「0.5 年」或「1.5 年」等小數。 For service years, always use float() — employees may have 0.5 or 1.5 years of service.
Lesson 04
多重條件 elif Multiple Conditions with elif
超過兩種情況時,用 elif 逐一判斷 When there are more than two outcomes, use elif to check each one
if / elif / else 結構 if / elif / else Structure

Python 從上到下逐一檢查,第一個成立的條件執行後,其餘全部跳過。 Python checks from top to bottom. Once the first true condition is found, all remaining conditions are skipped.

months = float(input("請輸入入職月數:Enter months of service: "))

if months < 3:
    print("試用期員工Probation Employee")
elif months < 36:
    print("初級員工Junior Employee")
elif months < 60:
    print("中級員工Mid-level Employee")
else:
    print("資深員工Senior Employee")
比較符號速查 Comparison Operators Quick Reference
符號Symbol 意思Meaning 注意事項Notes
<少於Less than—
>大於Greater than—
==等於Equal to⚠️ 雙等號!= 是賦值,== 才是比較Double equals! = assigns, == compares
<=少於或等於Less than or equal—
>=大於或等於Greater than or equal—
Lesson 05
迴圈 for + 清單 list for Loop + list
批量處理資料;合拼 for 與 if/elif 建立 HR 工具 Process data in bulk; combine for and if/elif to build an HR tool
清單 list — 一組資料 list — A collection of items
employees = ["James Tong", "陳大文Chan Tai Man", "李小明Lee Siu Ming"]
# 用 [ ] 包住,項目之間用逗號分隔Wrap in [ ], separate items with commas
for 迴圈 — 逐一處理每個項目 for Loop — Process each item one by one
for person in employees:
    print(f"正在處理:Processing: {person}")
Tuple — 綁定一對資料 Tuple — A paired set of data
employees = [
    ("James Tong", 2),
    ("陳大文Chan Tai Man", 14),
    ("李小明Lee Siu Ming", 38),
    ("王美華Wong Mei Wah", 72),
]
for name, months in employees:   # 「解包」同時取出兩個值Unpack both values at once
    print(f"{name}:{months} 個月months")
✅ 第一個 HR 工具:合拼 for + if/elif ✅ First HR Tool: Combining for + if/elif
for name, months in employees:
    if months < 3:
        status = "試用期員工Probation Employee"
    elif months < 36:
        status = "初級員工Junior Employee"
    elif months < 60:
        status = "中級員工Mid-level Employee"
    else:
        status = "資深員工Senior Employee"
    print(f"{name}:入職 Tenure: {months} 個月,狀態【months — Status: [{status}】]")
Lesson 06
函式 def / return Functions: def / return
把重複邏輯打包成可重用的工具 Package reusable logic into a named function
三個核心關鍵字 Three Core Keywords
關鍵字Keyword 作用Purpose 比喻Analogy
def定義函式(製作工具)Define a function (create the tool)製作標準作業流程表Write a standard procedure
參數Parameter函式的輸入空格Input slot for the function流程表上的空格Blank field in the procedure form
return把結果交回給呼叫者Send the result back to the caller填完表格後輸出結論Submit the completed form
有 return vs 沒有 return With return vs Without return
# ❌ 沒有 return — 只印出,結果無法再用No return — prints only, result cannot be reused
def print_status(months):
    if months < 3:
        print("試用期Probation")   # 做完即棄Use once, then gone

# ✅ 有 return — 結果可存起來,繼續使用With return — result can be stored and reused
def check_status(months):
    if months < 3:
        return "試用期員工Probation Employee"
    else:
        return "正式員工Confirmed Employee"

status = check_status(2)  # 接住結果Catch the result
print(f"狀態:Status: {status}")
✅ 完整版:函式 + 常數 + for 迴圈 ✅ Full Version: Function + Constant + for Loop
def check_status(months):
    PROBATION_MONTHS = 3    # 只需在這裡改一次Change only here to update everywhere
    if months < PROBATION_MONTHS:
        return "試用期員工Probation Employee"
    elif months < 36:
        return "初級員工Junior Employee"
    elif months < 60:
        return "中級員工Mid-level Employee"
    else:
        return "資深員工Senior Employee"

for name, months in employees:
    status = check_status(months)
    print(f"{name}:{status}")
💡
什麼時候用 return? 如果計算出來的結果之後還要用(存入變數、寫入報告、放進 f-string),就用 return。只需要即時顯示一次,可以不用。 When to use return? Use return when you need to store or reuse the result later (save to variable, write to report, embed in f-string). Skip it if you only need to display the result once.
📌 總速查表 📌 Master Cheat Sheet
概念Concept 語法Syntax HR 應用HR Use Case
輸出Outputprint("...")印出員工資料Display employee info
變數Variablename = "James"儲存姓名、月數Store name, months
f-stringf-stringf"Hello {name}"格式化員工報告Format HR reports
輸入User Inputinput("prompt")互動式查詢工具Interactive query tool
類型轉換Type Conversionint() / float()處理年資數字Handle numeric tenure
條件判斷Conditionalsif / elif / else判斷試用期狀態Determine probation status
迴圈Loopfor x in list:批量處理員工名單Batch process staff list
函式Functiondef fn(param): return可重用的狀態判斷工具Reusable status checker