TQC+ 程式語言Python常見指令
基本程式設計 (Basic Programming)
指令 (Command) | 描述 (Description) |
---|---|
int | 整數型別 (Integer type) |
float | 浮點數型別 (Floating point type) |
str | 字串型別 (String type) |
bool | 布林型別 (Boolean type) |
list | 串列型別 (List type) |
dict | 字典型別 (Dictionary type) |
set | 集合型別 (Set type) |
= | 賦值運算子 (Assignment operator) |
+ | 加法運算子 (Addition operator) |
- | 減法運算子 (Subtraction operator) |
* | 乘法運算子 (Multiplication operator) |
/ | 除法運算子 (Division operator) |
% | 取餘運算子 (Modulo operator) |
// | 整數除法運算子 (Floor division operator) |
** | 指數運算子 (Exponentiation operator) |
+= | 加等於運算子 (Add and assign operator) |
-= | 減等於運算子 (Subtract and assign operator) |
*= | 乘等於運算子 (Multiply and assign operator) |
/= | 除等於運算子 (Divide and assign operator) |
input() | 從使用者獲取輸入 (Get input from the user) |
print() | 輸出到控制台 (Output to the console) |
type() | 返回變數的型別 (Return the type of a variable) |
len() | 返回序列的長度 (Return the length of a sequence) |
range() | 生成數字序列 (Generate a sequence of numbers) |
sum() | 計算序列中元素的總和 (Calculate the sum of elements in a sequence) |
min() | 返回序列中的最小值 (Return the smallest value in a sequence) |
max() | 返回序列中的最大值 (Return the largest value in a sequence) |
abs() | 返回數字的絕對值 (Return the absolute value of a number) |
sorted() | 返回排序後的序列 (Return a sorted sequence) |
append() | 向串列添加元素 (Add an element to a list) |
remove() | 從串列中移除元素 (Remove an element from a list) |
pop() | 移除並返回串列中的最後一個元素 (Remove and return the last element of a list) |
clear() | 清空串列 (Clear all elements from a list) |
update() | 更新字典中的元素 (Update elements in a dictionary) |
keys() | 返回字典中的所有鍵 (Return all keys in a dictionary) |
values() | 返回字典中的所有值 (Return all values in a dictionary) |
items() | 返回字典中的所有鍵值對 (Return all key-value pairs in a dictionary) |
選擇敘述 (Selection Statements)
指令 (Command) | 描述 (Description) |
---|---|
if | 條件為真時執行代碼塊 (Execute a block of code if the condition is true) |
elif | 前一條件為假且當前條件為真時執行代碼塊 (Execute a block of code if the previous conditions were false and the current condition is true) |
else | 所有先前條件為假時執行代碼塊 (Execute a block of code if all previous conditions are false) |
switch | 根據變數的不同值執行不同代碼塊 (Execute different blocks of code based on the value of a variable; not natively available in Python, but can be mimicked using dictionaries) |
case | 在 switch 語句中定義不同的情況 (Define different cases in a switch statement; used in other languages like JavaScript, C++) |
default | 在 switch 語句中處理未匹配的情況 (Handle unmatched cases in a switch statement; used in other languages like JavaScript, C++) |
三元運算子 (Ternary Operator) | 根據條件返回不同的值 (Return a value based on a condition; syntax: value_if_true if condition else value_if_false ) |
match | 在 Python 3.10 引入的模式匹配 (Pattern matching introduced in Python 3.10 for more complex conditional logic) |
case | 在 match 語句中定義模式 (Define patterns in a match statement) |
迴圈敘述 (Loop Statements)
指令 (Command) | 描述 (Description) |
---|---|
for | 遍歷序列或可迭代對象的每一個元素 (Iterate over each element in a sequence or iterable object) |
while | 當條件為真時重複執行代碼塊 (Repeat executing a block of code while a condition is true) |
break | 提前終止迴圈 (Terminate the loop prematurely) |
continue | 跳過當前迭代的剩餘代碼,直接進入下一次迭代 (Skip the rest of the code in the current iteration and move to the next iteration) |
range() | 生成一個數字序列,常用於 for 迴圈 (Generate a sequence of numbers, commonly used in for loops) |
enumerate() | 同時獲取序列的索引和值,常用於 for 迴圈 (Get both index and value from a sequence, commonly used in for loops) |
zip() | 將多個可迭代對象配對組合,常用於 for 迴圈 (Pair elements from multiple iterables, commonly used in for loops) |
else | 在迴圈正常結束後執行的代碼塊 (A block of code executed after the loop finishes normally) |
nested loops | 在迴圈內嵌套另一個迴圈 (A loop inside another loop) |
進階控制流程 (Advanced Control Flow)
指令 (Command) | 描述 (Description) |
---|---|
try | 嘗試執行代碼塊,捕捉可能發生的異常 (Attempt to execute a block of code, catching any exceptions that may occur) |
except | 處理 try 代碼塊中發生的異常 (Handle exceptions that occur in the try block) |
finally | 無論是否發生異常,總是執行的代碼塊 (A block of code that always executes, regardless of whether an exception occurred) |
raise | 主動引發異常 (Manually raise an exception) |
assert | 用於調試的斷言語句,當條件為假時引發 AssertionError (A debugging aid that tests a condition, raising an AssertionError if the condition is false) |
with | 用於管理資源的上下文管理器 (Used to wrap the execution of a block of code with methods defined by a context manager) |
yield | 生成器函數中返回值,保存函數狀態供下次調用 (Return a value from a generator function and save the function's state for future calls) |
lambda | 創建匿名函數 (Create an anonymous function) |
pass | 空語句,用作佔位符 (A null statement used as a placeholder) |
函數 (Function)
操作 (Operation) | 描述 (Description) |
---|---|
def function_name(parameters): | 定義一個函式,包含函式名稱和參數 (Define a function with a name and parameters) |
return value | 從函式返回值 (Return a value from the function) |
function_name(arguments) | 調用函式並傳遞引數 (Call a function and pass arguments) |
lambda arguments: expression | 創建一個匿名函式 (Create an anonymous function) |
*args | 接收不定數量的參數 (Accept a variable number of positional arguments) |
**kwargs | 接收不定數量的關鍵字參數 (Accept a variable number of keyword arguments) |
docstring | 函式說明文件字串,用於描述函式的功能 (A string literal that describes the function's purpose) |
function_name.__name__ | 取得函式的名稱 (Get the name of the function) |
function_name.__doc__ | 取得函式的說明文件字串 (Get the docstring of the function) |
串列 (Lists)
操作 (Operation) | 描述 (Description) |
---|---|
list.append(x) | 在串列末尾添加元素 x (Add element x to the end of the list) |
list.extend(iterable) | 使用可迭代對象擴展串列 (Extend the list by appending elements from the iterable) |
list.insert(i, x) | 在指定位置 i 插入元素 x (Insert element x at position i) |
list.remove(x) | 移除串列中第一個值為 x 的元素 (Remove the first item from the list whose value is x) |
list.pop([i]) | 移除並返回指定位置 i 的元素,若未指定則移除並返回最後一個元素 (Remove and return the item at position i, or the last item if i is not specified) |
list.clear() | 移除串列中的所有元素 (Remove all items from the list) |
list.index(x[, start[, end]]) | 返回串列中第一個值為 x 的元素的索引 (Return the index of the first item whose value is x, within the optional start and end limits) |
list.count(x) | 返回串列中值為 x 的元素數量 (Return the number of times x appears in the list) |
list.sort(key=None, reverse=False) | 對串列中的元素進行排序 (Sort the items of the list in place) |
list.reverse() | 反轉串列中的元素順序 (Reverse the elements of the list in place) |
list.copy() | 返回串列的淺複製 (Return a shallow copy of the list) |
數組(Tuple)、集合(Set)以及詞典(Dictionary)
資料結構 (Data Structure) | 操作 (Operation) | 描述 (Description) |
---|---|---|
數組 (Tuple) | t = (1, 2, 3) | 創建一個數組 (Create a tuple) |
t[i] | 訪問數組中的元素 (Access an element in the tuple) | |
len(t) | 返回數組的長度 (Return the length of the tuple) | |
集合 (Set) | s = {1, 2, 3} | 創建一個集合 (Create a set) |
s.add(4) | 向集合中添加元素 (Add an element to the set) | |
s.remove(3) | 從集合中移除元素 (Remove an element from the set) | |
s.union({4, 5}) | 返回兩個集合的聯集 (Return the union of two sets) | |
詞典 (Dictionary) | d = {'a': 1, 'b': 2} | 創建一個詞典 (Create a dictionary) |
d['a'] | 訪問詞典中的值 (Access a value in the dictionary) | |
d['c'] = 3 | 添加或更新詞典中的鍵值對 (Add or update a key-value pair in the dictionary) | |
del d['b'] | 移除詞典中的鍵值對 (Remove a key-value pair from the dictionary) | |
d.keys() | 返回詞典中的所有鍵 (Return all keys in the dictionary) |
字串的運作 (String Operations)
操作 (Operation) | 描述 (Description) |
---|---|
str.upper() | 將字串中的所有字母轉換為大寫 (Convert all characters in the string to uppercase) |
str.lower() | 將字串中的所有字母轉換為小寫 (Convert all characters in the string to lowercase) |
str.capitalize() | 將字串的第一個字母轉換為大寫 (Convert the first character of the string to uppercase) |
str.title() | 將字串中每個單詞的首字母轉換為大寫 (Convert the first character of each word to uppercase) |
str.strip() | 移除字串兩端的空白符號 (Remove whitespace from both ends of the string) |
str.lstrip() | 移除字串左側的空白符號 (Remove whitespace from the left side of the string) |
str.rstrip() | 移除字串右側的空白符號 (Remove whitespace from the right side of the string) |
str.find(sub[, start[, end]]) | 返回子字串在字串中的最低索引,若未找到則返回 -1 (Return the lowest index of the substring, or -1 if not found) |
str.replace(old, new[, count]) | 將字串中的所有舊子字串替換為新子字串 (Replace all occurrences of the old substring with the new substring) |
str.split(sep=None, maxsplit=-1) | 將字串拆分為子字串列表 (Split the string into a list of substrings) |
str.join(iterable) | 將可迭代對象中的元素連接成一個字串 (Join elements of an iterable into a single string) |
str.format(*args, **kwargs) | 格式化字串 (Format the string using placeholders) |
str.isdigit() | 檢查字串是否只包含數字字符 (Check if the string consists only of digits) |
str.isalpha() | 檢查字串是否只包含字母字符 (Check if the string consists only of alpha |
檔案與異常處理 (File and Exception Handling)
操作 (Operation) | 描述 (Description) |
---|---|
open(file, mode) | 打開檔案並返回檔案對象 (Open a file and return a file object) |
file.read([size]) | 讀取檔案內容,若指定 size 則讀取指定大小的內容 (Read the contents of the file, optionally up to size bytes) |
file.readline() | 讀取檔案中的一行 (Read a single line from the file) |
file.readlines() | 讀取檔案中的所有行並返回列表 (Read all lines in the file and return them as a list) |
file.write(string) | 將字串寫入檔案 (Write a string to the file) |
file.writelines(lines) | 將多行寫入檔案 (Write a list of lines to the file) |
file.close() | 關閉檔案 (Close the file) |
with open(file, mode) as f | 使用上下文管理器打開檔案,自動處理檔案關閉 (Open a file using a context manager, automatically handling file closure) |
try | 嘗試執行代碼塊,捕捉可能發生的異常 (Attempt to execute a block of code, catching any exceptions that may occur) |
except Exception as e | 處理 try 代碼塊中發生的異常 (Handle exceptions that occur in the try block) |
finally | 無論是否發生異常,總是執行的代碼塊 (A block of code that always executes, regardless of whether an exception occurred) |
raise | 主動引發異常 (Manually raise an exception) |
assert | 用於調試的斷言語句,當條件為假時引發 AssertionError (A debugging aid that tests a condition, raising an AssertionError if the condition is false) |
參考資料:
- 蔡明志,財團法人中華民國電腦技能基金會,Python 3.x 程式語言特訓教材,碁峰資訊,臺北市
- 齊藤康毅,Deep Learning|用Python進行深度學習的基礎理論實作,吳嘉芳譯,碁峰資訊,臺北市
- TQC+ 程式語言Python 3認證
- TQC+ 程式語言Python 解答(全)
© 2024 Python語法指南 | 本網頁僅供參考