All Revision Notes

COM6001 Computing with Big Data · Week 2

Python Review 1: Environment, Data Types & Data Structures

COM6001 · Week 2 · Source: Lecture 02.pdf “Python review 1” (45 slides) · Lab 2 Q1–Q7

Contents · 14 sections

🎯 本講重點 (Learning outcomes)

  • 了解 computer program 同 Python 嘅特性 (scripting language、interpreted line-by-line)。
  • 分辨 IDE、editor、Jupyter notebook / Lab、Anaconda、Python interpreter、Python kernel。
  • 識用 Jupyter 嘅 code / markdown / raw cells 同 markdown heading 語法。
  • 掌握 main data types:int, float, str, bool;variables、assignment、is。
  • String 操作:indexing (positive / reverse)、slicing [start:stop:step] 及其 default values、methods、f-string。
  • 四種 data structures:list, tuple, set, dict — mutable 與否、語法、常用 methods。
  • Functions vs methods;用 help() / docstring 了解 return value。

⭐ 考試必溫 Top-5

  1. String slicing s[start:stop:step]:stop 唔包含;default values (尤其 step 為負數時)。
  2. List vs Tuple vs Set vs Dict:括號、ordered?、mutable?、duplicates?。
  3. Variables 係 references (pointers);is vs ==;a = b = c = 1 然後 a = 2 嘅結果。
  4. Function vs Method 分別;list.pop() 有 return value,list.append() return None。
  5. Variable naming rules + PEP 8 (snake_case / PascalCase / UPPER_SNAKE_CASE、4 spaces)。

1. Computer programs & Python

Slide 3:電腦做嘅嘢係 executing stored steps for computation or processing。Computer program 就係一系列要跟住做嘅步驟 (steps / flow),即係「how to」knowledge,用電腦明白嘅語言寫出嚟。

Slide 4 Python 特性:

  • 本科用 Python 3。
  • 易學:syntax 簡單,有大量 standard library 同 toolkits。
  • 係 scripting language,唔需要 run 之前先 compile;code 係 line-by-line 咁邊執行邊處理 (interpreted)。
  • Syntax 同 C-family (C, C++, Java, C#) 好唔同 (例如用 indentation 代替 { })。
  • Python programs 行得比 Java 同 C 慢。
💡 直覺理解

點解 Python 慢但 data science 仍然用佢?因為 pandas / numpy 底層係用 C 寫嘅,重活交畀 C 做;Python 負責「指揮」,寫得快、讀得明更重要。

2. IDEs & Environments

Slide 5:Python code 可以用普通 text editor 寫,存成 .py 檔。IDE (Integrated Development Environment) 係裝喺電腦令 coding 更方便嘅軟件,提供:folder operations、syntax highlighting、autocomplete、building executables、debugging。

做 data analysis / visualization (通常唔需要 executable) 建議用 Jupyter notebook:

  • 編輯同執行 .ipynb 檔而唔係 .py。
  • 語言仍然係 Python,但每個 cell 可以獨立執行,output 直接顯示喺同一個檔案入面。
  • 方便追蹤 data processing 進度同 debug。
Option類型優點注意
1. Anaconda Jupyter LabLocal本機無限使用;校內 lab 已安裝;Python 隨 Anaconda 一齊裝;pre-installed key packages、好多 data science 應用自己部機要裝 Anaconda;可能要自己裝 pandas, numpy, seaborn, plotly, scikit-learn
2. Visual Studio CodeLocal多語言 editor;auto-completion 反應快;UI 流暢;folder operations要另外下載 Python kernel;要裝 Jupyter extension 同各 packages
3. Google ColabCloud100% online、免安裝;pre-installed kernel 同主要 packages;易透過 Google Drive 分享免費帳戶 GPU / storage 有限;datasets 同 code 分開存,每次都要 mount Google Drive;內地用唔到

老師上堂主要用 Anaconda (slide 10),但你用邊個 IDE 都得。

Key terminologies (slide 9)

⭐ 考試重點:術語分清楚
  • IDE:不只係編輯 code,仲有 compilation、execution、debugging、version control、auto-completion、project-wide awareness 等 UI 功能。
  • VS Code:本質係 editor,靠大量 extensions / plugins 令佢「looks like」一個強大 IDE。
  • Jupyter notebook 係 Jupyter Lab 嘅核心;Jupyter Lab 係支援 notebook 檔案嘅 IDE。
  • Anaconda 不只係 IDE,而係 environment manager,提供一系列 IDEs (VS Code, PyCharm, Spyder, Jupyter…)。
  • Python = programming language (規則同藍圖);Python interpreter = 明白呢種語言並執行 code 嘅引擎;Python kernel = 你嘅 code 同 interpreter 之間嘅 interface。三者 version number (幾乎) 一樣 — 揀 kernel version 即係揀 Python 同 interpreter 嘅 version。
🖼️ 圖片內容

Slides 6–8、10–14 主要係 Anaconda / VS Code / Colab 介面截圖同步驟圖,截圖內容擷取不到;請對照原 slides 第 6–14 頁。文字步驟已整理如下。

Launch Jupyter Lab & Hello World (slides 11–14)

  1. 開 terminal:Windows 搜尋並打開 Anaconda Prompt (Anaconda3);Mac 開 Terminal 打 conda activate base。
  2. 打 jupyter lab。校內電腦只可用 D drive,要加 --notebook-dir=D:/。
  3. 左邊 sidebar 係你開 Jupyter Lab 嗰個目錄;新增 folder → 入去 → Notebook → Python (conda env base)。
  4. Rename notebook;cell 入面打 print("Hello World!");按 Shift + Enter 執行。

VS Code:File → Open Folder (例如 D:/COM6001/Week_2/) → 裝 Jupyter extension → File → New File → Jupyter Notebook → 存為 Lab_2_<your name>.ipynb。Cell 左邊 [1] 係 Execution Count (執行次序),下面係 output。

print("Hello World!")   # Shift + Enter 執行
# 輸出:Hello World!

3. Jupyter cell types & Markdown

Cell type用途特點
Code cell寫 code statements會執行,有 output 同 execution count
Markdown cell寫 narrative texts# 開頭 = heading;*text* = italic;**text** = bold;Shift+Enter = render 顯示
Raw cell (Anaconda only)Plain textNo input-output distinction;not rendered;not executed

Heading 層級 (slide 16):# abc = level-1、## abc = level-2、### abc = level-3,如此類推。Lab Q1 就係新增 markdown cell 打 # Q2:Variables。

🖼️ 圖片內容

Slide 16 右邊嘅 keyboard shortcuts 表係圖片,文字擷取不到;請對照原 slide 第 16 頁。(常見 Jupyter shortcut:command mode 下 M 轉 markdown、Y 轉 code、A/B 喺上/下新增 cell — 此為一般知識,未必與 slide 相同。)

4. Learning a programming language & PEP 8

Slide 17 列出學一門語言要掌握:Syntax、Main data types and data structures、The controlling logic、How to make functions、How to run、Code every day — “Learn by Doing, Not Just Reading/Asking AI”。

  • 永遠要 rename 檔案,唔好交 untitled1.ipynb!
⭐ 考試重點:PEP 8 (de facto Python style guide)
  • snake_case → variables 同 functions,例如 my_int, calculate_area()
  • PascalCase → classes,例如 DataFrame
  • UPPER_SNAKE_CASE → constants,例如 MAX_SIZE
  • 每層 indentation 用 4 spaces;逗號後加空格,operators 兩邊加空格 (a = 1,唔係 a=1)。

Generative AI usage (slide 18)

「Gen AI is your worker, not your manager!」不同階段可以點用:

StageDosDon'ts
Beginner (Weeks 2–3)code explanation, error explanationdirectly give the code
Intermediate (Weeks 4–11)+ function suggestion, sample snippets (< 10 lines)directly give the code for the question
Project (Weeks 12+)ideation, analysis ideas, API / library suggestion, sample codes in your contextdirectly give the implementation / draw analysis for you

GenAI 答案可能有 bias,要 double check;最重要係自己消化 — 因為 tests / exam 係 paper-based close-book,仲有 oral presentation。

5. Main Data Types

Exam Slide 20:

類別Type存咩例子
NumericintIntegers6001, -3
floatNumbers with a decimal point70.2, 1.0
Non-numericstrOrdered sequences of characters'john'
boolLogical values (binary)True / False

Slide 21:Data structures 可以裝一堆 (唔同類型嘅) data objects;Python 容許同一個 data structure 入面放唔同 type 嘅元素 (例如 ['com', 6001, 'john', 70.2])。

6. Variables & Assignment

Slide 22:Variables 係用嚟存單一 data 或 data structure 嘅 containers。

  • Python 冇 declare variable 嘅指令;第一次 assign value 嗰刻就建立咗。
  • 唔使指定 type,之後仲可以改 type — Python 會自動揀最合適嘅 type (dynamic typing)。
  • 想指定 type 用 casting:int(), float(), str()。
  • 用 type() 睇 variable 嘅 type。
x = 5            # int
x = "five"       # 同一個 variable 可以改 type → str
y = float(3)     # casting → 3.0
z = int("42")    # casting → 42
print(type(x), type(y), type(z))
# <class 'str'> <class 'float'> <class 'int'>

Rules for variable names (slide 23)

  • 唔可以用數字開頭 (2nd_name ✗)
  • 名入面唔可以有空格 (my name ✗)
  • Case sensitive (Age 同 age 係兩個 variable)
  • 避免用 special keywords / built-in 名,否則會改變佢原本意思
⚠️ 常見錯誤

Slide 23 示範咗 print = 1:之後 print 變咗一個值為 1 嘅 variable,再 call print("hi") 會出 TypeError: 'int' object is not callable。同樣,Lab Q4 用咗 str = 'Hello, World!' 做 variable 名,會蓋過 built-in str() function — 實際寫 code 時應避免 (用 del str 可還原)。

Assignment, references 同 is (slide 24)

= 係 assignment operator:x = 1 把 value 1 assign 畀名為 x 嘅 variable。Variable 亦可以 assign 畀另一個 variable。

Exam 重點:喺 Python,variables (names) 只係指向 objects 嘅 references / pointers。用 is operator 檢查兩個 variables 係咪指向同一個 object;用 whos (Jupyter magic) 列出 workspace 所有 variables。

a = b = c = 1     # a, b, c 全部指向同一個 object 1
print(a is b, b is c)   # True True
a = 2             # a 改為指向另一個 object 2;b, c 仍指向 1
print(a is b)     # False
print(b is c)     # True
print(a == 2)     # True  —— == 比較「值」,is 比較「係咪同一個 object」
💡 直覺理解 (Lab Q3)

想像 object 係一個盒,variable 名係貼喺盒上嘅標籤。a = 2 唔係「改盒入面嘅嘢」,而係把 a 呢張標籤撕走、貼去另一個盒 (2)。所以 b、c 完全唔受影響。

🖼️ 圖片內容

Slides 22–24 嘅 code 示範 (包括 whos 輸出同 pointer 示意圖) 係截圖,文字擷取不到;請對照原 slides 第 22–24 頁。以上 code 為按 slide 文字重寫。

Lab Q2:建立 my_int、my_float、my_string 並加 comment:

my_int = 6001          # this is an int number
my_float = 70.2        # this is a float number
my_string = "COM6001"  # this is a string

7. Working with Strings

7.1 Basics (slide 27)

  • String 用引號包住,單引號或雙引號都得,但要成對;可以互相嵌套:"this is the 'abc' book"。
  • 用 + 連接 strings。
  • '\n' = 換行。
  • print() 印出 string。
s1 = "Hello"
s2 = 'World'
print(s1 + ", " + s2 + "!")       # Hello, World!
print("line 1\nline 2")           # \n 換行
print("this is the 'abc' book")   # 雙引號入面用單引號

7.2 Indexing (slide 28)

String 係 sequence of characters,可用 index 攞單一字元。長度 N 嘅 string 有兩種 indexing:

  • Positive index:由 0 到 N-1
  • Reverse index:由 -1 (最後一個) 到 -N (第一個)
charHello,␣World!
positive0123456789101112
reverse-13-12-11-10-9-8-7-6-5-4-3-2-1

7.3 Slicing s[start:stop:step] (slide 29)

Exam Slicing = 由 string 攞一段 characters:

  • start:開始嘅 index (包含)。Default 0。
  • stop:up to but not included 嗰個位置。Default = 該方向嘅盡頭 (包括盡頭)。
  • step:每次跳幾多。Default 1。
  • 三個都可以省略,省略就用 default。
⭐ 考試重點:slicing 規則
  • 結果長度 (step = 1 時) = stop − start。例:s[2:5] 攞 index 2, 3, 4 共 3 個字。
  • step 為負時,方向反轉:default start 變成最後一個字 (-1),default stop 變成超越開頭 (包含 index 0)。
  • 如果 start 喺 stop 嘅「錯誤方向」(例如 step 正但 start > stop),結果係空 string '' — 呢個就係 slide 29 「Why empty?」嘅答案。
s = 'Hello, World!'
print(s[0:5])     # 'Hello'      index 0–4
print(s[7:])      # 'World!'     由 7 到盡頭
print(s[:5])      # 'Hello'      由 0 開始
print(s[::2])     # 'Hlo ol!'    每隔一個
print(s[-6:-1])   # 'World'      -1 唔包含
print(s[5:2])     # ''           step 預設 +1,但 5 > 2 → 空 (Why empty?)
print(s[5:2:-1])  # ',ol'        反方向就得:index 5, 4, 3
🖼️ 圖片內容

Slides 27–29 嘅 code 示範係截圖,slide 29 「Why empty?」所指嘅具體例子文字擷取不到;請對照原 slide 第 29 頁。上面 s[5:2] 係用嚟解釋同一原理嘅例子。

Lab Q5: Default values in slicing (slide 33)

s = 'Hello, World!'
print(s[::])     # 'Hello, World!'
print(s[::-1])   # '!dlroW ,olleH'
print(s[0::-1])  # 'H'
print(s[:-1:])   # 'Hello, World'
#ExpressionstartstopstepOutput
1s[::]0very end of forward direction (incl. last)1Hello, World!
2s[::-1]-1 (last char)very end of backward direction (incl. index 0)-1!dlroW ,olleH
3s[0::-1]0very end of backward direction (incl. index 0)-1H
4s[:-1:]0-1 (excluded)1Hello, World
💡 直覺理解

Q5 第 3 題:由 index 0 開始向左行,左邊已經冇字,所以只得 'H'。關鍵係:省略 stop 時佢會行到該方向盡頭並包括盡頭。

8. Functions vs Methods; String methods & f-string

Slide 30:兩者都係可重用嘅 code,可以喺程式任何地方 「call」,令 code 模組化、唔使重複寫。

FunctionMethod
定義獨立於任何 object / class 定義同某個 object / class 綁定 (light functions that only belong to certain objects)
點 call直接用名 + arguments:print(st), len(st)一定要用 object 嚟 call:st.upper()
例子print("Hello World!")st.find("s", 0, 6) — 喺 slice 0 到 6 搵字母 s
⚠️ 常見錯誤

int.upper() 會出錯 — int class 冇 upper method。Method 只屬於特定 type 嘅 objects。

String methods (slide 31):.find() (搵 substring 位置,搵唔到 return -1)、.upper()、.lower()。

f-string:string 前面加 f 或 F,{ } 入面可以放 Python expressions,執行時會換成其值。

st = "Hello, World!"
print(st.upper())          # HELLO, WORLD!
print(st.lower())          # hello, world!
print(st.find("o"))        # 4  (第一個 o 嘅 index)
print(st.find("o", 5))     # 8  (由 index 5 開始搵)
print(st.find("z"))        # -1 (搵唔到)
n = len(st)
print(f"There are {n} chars in this string")       # There are 13 chars in this string
print(f"2 + 3 = {2 + 3}, upper: {st.upper()}")     # { } 入面可以係任何 expression

Lab Q4 參考答案 (slide 32)

s = 'Hello, World!'          # slide 用 str 做名,但建議避免蓋過 built-in str
print(s)                     # complete string
print(s[0])                  # first character → 'H'
print(s[2:5])                # 第三至第六 (exclusive) → 'llo'
print(s[-1:-4:-1])           # 最後三個字倒轉 → '!dl'
print(s + "TEST")            # 'Hello, World!TEST'
print(f"There are {len(s)} chars in this string")   # 13
⚠️ 留意

「the third to sixth (exclusive)」有兩種理解:如果「third」指第 3 個字 (index 2),答案係 s[2:5];如果指 index 3,就係 s[3:6] = 'lo,'。考試作答時寫明你嘅理解。

9. Boolean

Slide 34:Boolean variable 只可以係 True 或 False (第一個字母大寫)。Boolean 係 conditions / assertions 返回嘅 type。

print(3 > 2)          # True
print(type(3 == 2))   # <class 'bool'>
flag = true           # ✗ NameError:要寫 True

10. Main Data Structures: list, tuple, set, dict

Exam Slide 35:

Structure類別括號Ordered?Mutable?Duplicates?Access
ListSequence[ ]✓✓ (can be changed after creation)✓index l[0]
TupleSequence( )✓✗✓index t[0]
DictionaryMapping{key: value}slide 寫 unordered*✓keys uniquekey d['name']
SetSet type{ } / set()✗ unordered✓ (可 add)✗ unique only冇 index

*Week 3 補充:Python 3.7 之後 dict 會保留 insertion order。

10.1 List methods & functions (slide 36)

  • Methods:.sort()、.append(x) (加到尾)、.pop(i) — remove and return item at index i,default index = 最後一個。
  • Functions:len()、max()、min()。
nums = [3, 1, 2]
nums.append(5)       # [3, 1, 2, 5]
nums.sort()          # [1, 2, 3, 5]  (in-place,冇 return)
last = nums.pop()    # 移除並返回 5 → nums = [1, 2, 3]
first = nums.pop(0)  # 移除並返回 1 → nums = [2, 3]
print(len(nums), max(nums), min(nums))   # 2 3 2

10.2 Tuples (slide 37)

Tuple 用一個 variable 存多個 items,係 ordered and unchangeable — 一經 assign,元素就唔可以改。

Why do we need tuples? 因為 immutable 嘅特性保證元素唔會被改動,確保 data integrity,喺某些情況好重要 (例如做 dict key、儲存座標 / 設定值)。

my_tup = ('com', 6001, 'john', 70.2)
print(my_tup[1])        # 6001
my_tup[2] = 'Aileen'    # TypeError: 'tuple' object does not support item assignment

10.3 Sets (slide 38)

由 unique member elements 組成;用 { } 直接建立或者 set() function。

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5}
s1.add(10)          # .add() 加新元素 → {1, 2, 3, 4, 10}
print(s1 - s2)      # {1, 2, 10}  只喺 s1 出現 (difference)
print(s2 - s1)      # {5}         只喺 s2 出現
print(s1 & s2)      # {3, 4}      共同元素 (intersection)
s1.add(3)           # 3 已存在 → set 不變
empty = set()       # 注意:{} 係空 dict,唔係空 set!

10.4 Dictionary (slide 39)

以 key-value pair 形式存 objects 嘅 mapping。

  • Construction:{key: value, key: value, ...}
  • Insertion:dict[new_key] = new_value
  • Retrieval:dict[key_name] — 例如用 key "name" 攞返 value "mango"
fruit = {"name": "mango", "price": 12}
print(fruit["name"])     # mango
fruit["color"] = "yellow"   # insertion
fruit["price"] = 15         # 同一 key 再 assign = update
🖼️ 圖片內容

Slides 35–39 嘅 code 示範係截圖,文字擷取不到;請對照原 slides 第 35–39 頁。以上 code 依 slide 文字重寫。

Lab Q6 參考答案 (slide 40)

my_list = ['com', 6001, 'john', 70.2]
my_tup  = ('com', 6001, 'john', 70.2)
my_set  = {'com', 6001, 'john', 70.2}
my_dict = {'name': 'john', 'mark': 70.2}

my_list[2] = 'Aileen'      # 5. 第三個元素 index = 2
print(my_list)             # ['com', 6001, 'Aileen', 70.2]

# 6. my_tup[2] = 'Aileen' → TypeError:tuple 係 immutable,建立後唔可以改

my_list.pop(1)             # 7. 移除第二個元素 (6001);亦可 del my_list[1]
print(my_list)             # ['com', 'Aileen', 70.2]

my_set.add('com')          # 8. 'com' 已經存在,set 只存 unique elements,所以冇加到
print(my_set)

print(my_dict['mark'])     # 9. 70.2

11. Getting help & Return values

Slide 41:官方說明有兩種來源:

  • Docstring:寫喺 source code 入面,用三引號 """ 包住,放喺 function / class definition 下面。
  • Official Documentation:外部網站 (例如 docs.python.org) 同 API references。

Slide 42 四種即時求助方法:

  1. Mouse hover (IDE tooltips):VS Code / Pylance 自動彈出 docstring。
  2. help() function:help(list.append) — Pro-tip:唔好加 (),咁 Python 會讀個 function 而唔係執行佢。
  3. __doc__ attribute:print(list.append.__doc__),直接印 raw docstring。
  4. Keyboard shortcut:cursor 放喺括號入面按 Ctrl + Shift + Space (Mac: Cmd + Shift + Space) 睇 parameter hints。
help(list.pop)
# pop(index=-1, /) method of builtins.list instance
#     Remove and return item at index (default last).
#     Raises IndexError if list is empty or index is out of range.
print(list.append.__doc__)
# Append object to the end of the list.
⭐ 考試重點:Lab Q7 Return value
my_list = [1, 2, 3]
print(my_list.pop(0))      # 1     ← pop 會 "Remove and RETURN item"
print(my_list.append(0))   # None  ← append 只係 in-place 修改 list,冇 return statement

解釋:print() 印出嘅係 method 嘅 return value。pop() 嘅 docstring 寫明 “Remove and return item”,所以印到被移除嘅元素;append() 只係 “Append object to the end of the list”,直接修改原本嘅 list,冇 return 任何嘢,Python 嘅 function 冇 return 時預設返回 None。同理 list.sort() 都係 return None。

⚠️ 常見錯誤

my_list = my_list.append(4) — 呢句之後 my_list 變咗 None!in-place methods 唔好 assign 返落去。

12. Lab submission & Summary

Slide 44:答晒 Q1–Q7,rename 做 Lab_2_<your name>.ipynb,交 PDF (Colab / Anaconda 直接 print to PDF;VS Code 用 More Actions → Export → HTML 再由 browser print),檢查所有答案同 output 都印得清楚。

Summary (slide 45):Python characteristics;basic data types and structures;string manipulations;string slicing and indexing;slicing of data structures;data structures and their methods。

自我測驗 Self-test

Q1. Python 點解叫 scripting language?同 C / Java 比較有咩優缺點?

Python 唔需要 run 之前先 compile,code 係執行時 line-by-line 處理。優點:syntax 簡單易學、大量 libraries;缺點:行得比 Java 同 C 慢。

Q2. Python、Python interpreter、Python kernel 有咩分別?

Python 係 programming language (規則同藍圖);interpreter 係明白並執行 Python code 嘅引擎;kernel 係你嘅 code (例如 notebook) 同 interpreter 之間嘅 interface。三者 version number 幾乎一樣,揀 kernel version 即係揀 Python version。

Q3. s = 'Data Science'。寫出 s[0:4]、s[-7:]、s[::-1]、s[5:2]、s[::3] 嘅結果。

s[0:4] = 'Data';s[-7:] = 'Science';s[::-1] = 'ecneicS ataD';s[5:2] = '' (step 預設 +1,start > stop → 空);s[::3] = index 0,3,6,9 → 'D', 'a', 'c', 'n' → 'Dacn'。

Q4. 執行 a = b = c = 1; a = 2 之後,a is b 同 b is c 係咩?點解?

a is b → False;b is c → True。Variables 只係指向 object 嘅 references。一開始三個都指向 object 1;a = 2 令 a 改為指向 object 2,b 同 c 仍然指向 1。

Q5. 比較 list、tuple、set、dict:邊個 immutable?邊個唔可以有重複?邊個用 key 存取?

Tuple immutable;set 只容許 unique elements (dict 嘅 keys 亦必須 unique);dict 用 key 存取 (d[key])。List 同 tuple 係 ordered sequences 用 index 存取;set unordered 冇 index。

Q6. print(my_list.append(0)) 點解印出 None?

append() 係 in-place 修改 list,冇 return value;Python function / method 冇 return 時預設 return None。相反 pop() 會 remove and return 該 item,所以印到元素。

Q7. Function 同 method 有咩分別?各舉一例。

Function 獨立定義,直接用名 call,例如 len(s)、print(s)。Method 屬於某個 object / class,要經 object call,例如 s.upper()、my_list.append(1);int 冇 upper() method。

Q8. 以下邊啲 variable 名合法?2data, my data, myData, _temp, print

2data ✗ (數字開頭);my data ✗ (有空格);myData ✓ (合法但 PEP 8 建議 my_data);_temp ✓;print 語法上可以但應避免,會覆蓋 built-in function。

Q9. s1 = {1,2,3}; s2 = {2,3,4}。s1 - s2、s2 - s1、s1 & s2 係咩?

s1 - s2 = {1};s2 - s1 = {4};s1 & s2 = {2, 3}。

一頁總結 Cheat sheet

⭐ 考前速記
  • Python 3 = scripting language,無需 compile,line-by-line 執行;比 C / Java 慢。
  • IDE ≠ editor (VS Code) ≠ environment manager (Anaconda);Jupyter Lab 係支援 notebook 嘅 IDE;kernel = code ↔ interpreter 嘅 interface。
  • Cells:code / markdown (# heading, *italic*, **bold**) / raw;Shift + Enter 執行。
  • PEP 8:snake_case (var / func)、PascalCase (class)、UPPER_SNAKE_CASE (const)、4 spaces。
  • Types:int, float, str, bool (True/False 大寫);type() 睇類型;casting int()/float()/str()。
  • Variable = reference;is 比較同一 object,== 比較值;名唔可以數字開頭、有空格;case sensitive;避免 keywords。
  • Index:0…N−10 \dots N-1 / −1⋯−N-1 \dots -N。Slicing [start:stop:step]:stop 唔包含;defaults 0 / 盡頭(含) / 1;step 負 → 由尾向頭;方向錯 → ''。
  • String:+ 連接、\n 換行、.find() (搵唔到 −1)、.upper()、.lower()、f"{expr}"。
  • List [] mutable · Tuple () immutable (data integrity) · Set {} unique, - difference, & intersection, .add() · Dict {k: v}, d[k] = v 插入, d[k] 取值。
  • List:.sort(), .append() (return None), .pop(i) (remove & return,default 最後);len/max/min。
  • Help:hover、help(list.append) (唔加括號)、.__doc__、Ctrl+Shift+Space。