
- Python基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python控制語句
- Python - 控制流
- Python - 決策
- Python - if語句
- Python - if else
- Python - 巢狀if
- Python - Match-Case語句
- Python - 迴圈
- Python - for迴圈
- Python - for-else迴圈
- Python - while迴圈
- Python - break語句
- Python - continue語句
- Python - pass語句
- Python - 巢狀迴圈
- Python函式與模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅關鍵字引數
- Python - 位置引數
- Python - 僅位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS檔案/目錄方法
- Python - OS路徑方法
- 面向物件程式設計
- Python - OOPs概念
- Python - 類與物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python錯誤與異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except塊
- Python - try-finally塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀try塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python網路程式設計
- Python - 網路程式設計
- Python - 套接字程式設計
- Python - URL處理
- Python - 泛型
- Python庫
- NumPy教程
- Pandas教程
- SciPy教程
- Matplotlib教程
- Django教程
- OpenCV教程
- Python雜項
- Python - 日期與時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI程式設計
- Python - XML處理
- Python - GUI程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python實用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 實用資源
- Python - 討論
- Python編譯器
- NumPy編譯器
- Matplotlib編譯器
- SciPy編譯器
Python速查表
這份Python速查表對學生和開發者快速學習Python程式設計很有幫助。
列印Hello World
列印“Hello, World!”是一個基本程式。要列印“Hello, World”,請使用print()函式。這是一個基本的Python程式:
print("Hello, World!") # Output: Hello, World!
列印輸出
**print()函式**也可以用來列印輸出,即變數的值到螢幕上。
name = "Kelly Hu" print("Hi my name is: ", name)
要列印多個變數,可以使用以下print()函式的級聯形式:
name = "Kelly Hu" age = 27 city = "Brentwood" print("I am", name, ". I'm", age, "years old and lives in", city)
不換行列印
print()方法在列印結果後會插入一個換行符。要實現不換行列印,請在print()方法中使用end=' '引數作為最後一個引數。
print("Hello", end=" ") print("World")
您可以為**end**引數指定任何值;新分配的值將在結果之後列印。
print("Hello", end="####") print("World")
註釋
Python提供了三種類型的註釋:
- 單行註釋
- 多行註釋
- 文件字串註釋
1. 單行註釋
單行註釋後面跟著井號(#)。
# This is single-line comment
2. 多行註釋
多行註釋寫在三個單引號(''' )之間。在'''和'''之間編寫的任何內容都表示多行註釋。
''' name = "Kelly Hu" age = 30 city = "Brentwood" ''' print("Hello, World!")
變數
Python變數是在您為其賦值時建立的。Python中沒有用於宣告變數的關鍵字。
name = "Kelly Hu" age = 27 print(name) print(age)
指定變數的資料型別
可以使用型別轉換(藉助於str()、int()、float()等內建函式)來指定變數的資料型別。
a = str(123) b = int(123) c = float(123) # Printing type print(type(a)) print(type(b)) print(type(c))
列印變數/物件的型別
type()函式可用於列印變數或物件的資料型別(物件型別)。
name = "Kelly Hu" print(name, "is the type of", type(name))
變數名
變數名(或識別符號)必須以字母或下劃線字元開頭,並且僅允許字母數字字元和下劃線作為變數名。
一些有效的變數名:**name**、**_name**、**my_name**、**name2**、**MY_NAME**
為變數賦值多個值
可以透過逗號分隔變數名和值來為變數賦值多個值。
name, age, city = "Kelly Hu", 27, "Brentwood" print(name) print(age) print(city)
資料型別
以下是Python資料型別:
1. 文字型別:字串 (str)
text = "Hello, World!"
2. 數值型別
int
num_int = 10
float
num_float = 10.5
complex
num_complex = 2 + 3j
3. 序列型別
list
my_list = [1, 2, 3]
tuple
my_tuple = (1, 2, 3)
range
my_range = range(1, 10)
4. 對映型別:字典 (dict)
my_dict = {"name": "Kelly Hu", "age": 27}
5. 集合型別
set
my_set = {1, 2, 3}
frozenset
my_frozenset = frozenset([1, 2, 3])
6. 布林型別:bool
my_bool = True
7. 二進位制型別
bytes
my_bytes = b"Hello"
bytearray
my_bytearray = bytearray(5)
memoryview
my_memoryview = memoryview(b"Hello")
8. None型別:NoneType
my_none = None
運算子
Python運算子用於對運算元執行各種運算,例如算術運算、邏輯運算等。
算術運算子
Python算術運算子包括+(加法)、-(減法)、*(乘法)、/(除法)、//(地板除)、%(取模)和**(指數) 。
賦值運算子
Python賦值運算子用於將值賦給變數,包括=、+=、-=、*=、/=、%=、**=、//=、&=、|=、^=、>>=和<<=。
比較運算子
Python比較運算子用於比較兩個值,包括==(等於)、!=(不等於)、>(大於)、<(小於)、>=(大於等於)和<=(小於等於)。
邏輯運算子
Python邏輯運算子為**and**、**or**和**not**。
身份運算子
Python身份運算子為**is**和**is not**,用於檢查兩個變數是否引用記憶體中的同一個物件。
成員運算子
Python 成員運算子是 **in** 和 **not in**。這些運算子用於測試某個值是否在一個序列中。
位運算子
Python 位運算子對二進位制值執行運算;這些運算子包括 AND (&)、OR (|)、NOT (~)、XOR (^)、左移 (<<) 和右移 (>>)。
使用者輸入
Python 允許你從使用者那裡獲取不同型別的 輸入。input() 函式用於從使用者獲取字串型別的輸入。你可以使用以下基本方法將輸入轉換為特定型別:
基本使用者輸入
name = input("Enter your name: ") print("Hello", name)
整數輸入
age = int(input("Enter your age: ")) print(f"You are {age} years old.")
浮點數輸入
x = float(input("Enter any float value: ")) print(x)
處理無效輸入
你可以使用 try 和 except 來處理無效輸入。
try: x = int(input("Input an integer value: ")) print(x) except ValueError: print("Please enter a valid number.")
條件語句
Python 條件語句 使用 **if**、**elif** 和 **else** 關鍵字編寫。
a = 10 b = 20 if a > b: print("a is greater than b") elif b > a: print("b is greater than a") else: print("a is greater than b")
迴圈
有兩種型別的 Python 迴圈 − for 迴圈 和 while 迴圈。
for 迴圈
students = ["Kelly Hu", "Akanksha", "Peter"] for s in students: print(s)
while 迴圈
i = 1 while i <= 10: print(i) i += 1
字串
Python 字串 是用單引號或雙引號括起來的字元序列。
列印字串
print("I'm Kelly Hu I live in Brentwood") name, city = "Kelly Hu", "Brentwood" # Printing string variables print("I'm", name, "I live in", city)
引號巢狀
你可以使用 print() 函式列印引號作為字串。
print("I'm Kelly Hu") print("I am 'Kelly Hu'") print("I am \"Kelly Hu\"")
多行字串
Python 允許將多行字串賦值給變數。只需使用三個單引號或雙引號來表示多行字串即可。
a = """I am Kelly Hu I lives in Brentwood. I am 27 years old""" b = '''I am Kelly Hu I lives in Brentwood. I am 27 years old''' print(a) print(b)
字串切片
字串切片可以透過使用起始索引和結束索引來完成,這兩個索引之間用冒號分隔,並用方括號括起來。
test = "Hello, World!" print(test[2:5]) print(test[0:]) print(test[:13]) print(test[:5])
字串連線
你可以使用加號 (+) 運算子連線兩個或多個字串。
name = "Kelly Hu" city = "Brentwood" person = name + " " + city print(person)
字串格式化
字串格式化使用 Python f-string 完成。
name = "Kelly Hu" age = 27 person = f"My name is {name}, I am {age} years old" print(person)
字串方法
以下是常用的 字串方法:
序號 | 方法及描述 |
---|---|
1 |
將字串的首字母大寫 |
2 |
將字串中的所有大寫字母轉換為小寫。類似於 lower(),但也可用於處理 Unicode 字元 |
3 |
將字串中的所有大寫字母轉換為小寫。 |
4 |
反轉字串中所有字母的大小寫。 |
5 |
返回字串的“標題”版本,即所有單詞以大寫字母開頭,其餘字母為小寫。 |
6 |
將字串中的小寫字母轉換為大寫。 |
跳脫字元
Python 跳脫字元 是轉義符 (\) 和字元的組合,用於執行特定任務。以下是跳脫字元及其含義:
跳脫字元 | 描述 | 示例 |
---|---|---|
\\ | 反斜槓 | print("This is a backslash: \\") |
\' | 單引號 | print('It\'s a sunny day!') |
\" | 雙引號 | print("He said, \"Hello!\"") |
\n | 換行符 | print("Hello\nWorld") |
\r | 回車符 | print("Hello\rWorld") |
\t | 水平製表符 | print("Hello\tWorld") |
\b | 退格符 | print("Hello\bWorld") |
\f | 換頁符 | print("Hello\fWorld") |
\v | 垂直製表符 | print("Hello\vWorld") |
\ooo | 八進位制值(用八進位制數表示的字元) | print("\101") # 列印 'A' |
\xhh | 十六進位制值(用十六進位制數表示的字元) | print("\x41") # 列印 'A' |
列表
Python 列表用於儲存以逗號分隔的值。
建立列表
# Empty list my_list = [] # List with elements my_list = [1, 2, 3, 4, 5]
訪問元素
可以使用索引和列表切片來訪問列表的元素。
my_list = [1, 2, 3, 4, 5] print(my_list[0]) print(my_list[2]) print(my_list[-1]) print(my_list[2:4])
追加和插入元素
可以使用 list.append() 和 list.insert() 方法分別追加和插入列表中的元素。
my_list = [1, 2, 3, 4, 5] print(my_list) my_list.append(6) my_list.insert(0, 0) print(my_list)
刪除列表元素
remove() 方法用於刪除列表中的元素。
my_list = [1, 2, 3, 4, 5] print(my_list) my_list.remove(3) print(my_list)
複製列表
list.copy() 方法用於將一個列表複製到另一個列表。
my_list = [1, 2, 3, 4, 5] new_list = my_list.copy() print(my_list) print(new_list)
清空列表
list.clear() 方法用於清空列表元素。
my_list.clear()
巢狀列表
Python 巢狀列表指的是列表中的列表。
nested_list = [[1, 2], [3, 4], [5, 6]] print(nested_list)
元組
Python 元組 用於在一個變數中儲存多個以逗號分隔的值。元組值放在圓括號內。
建立元組
my_tuple = (1, 2, 3) print(my_tuple)
建立空元組
my_tuple = () print(my_tuple)
無括號的元組(隱式元組)
my_tuple = 1, 2, 3 print(my_tuple)
單元素元組
my_tuple = (1,) print(my_tuple)
訪問元組元素
可以使用索引和元組切片來訪問元組的元素。
my_tuple = (10, 20, 30) print(my_tuple[0]) print(my_tuple[1]) print(my_tuple[0:]) print(my_tuple[-1]) print(my_tuple[0:2])
元組連線
要連線元組,請使用加號 (+) 運算子。
tuple1 = (10, 20, 30) tuple2 = (40, 50) print(tuple1 + tuple2)
元組解包
tuple1 = (10, 20, 30) a, b, c = tuple1 print(a) print(b) print(c)
巢狀元組
nested_tuple = ((10, 20), (30, 40), (50, 60)) print(nested_tuple)
集合
Python 集合 是多個專案的集合,這些專案是無序的、不可更改*的和無索引的。集合值以逗號分隔,並用花括號括起來。
建立集合
set1 = {10, 20, 30, 40, 50} # Set from a list set2 = set([10, 20, 30, 40, 50]) print(set1) print(set2)
新增和刪除元素
以下函式用於向集合中新增和刪除元素:
- add() − 新增單個元素。
- update() − 新增多個元素。
- remove() − 刪除元素。
- discard() − 安全地刪除元素。
- pop() − 刪除並返回任意元素。
- set.clear() − 清空集合。
集合運算示例
set1 = {10, 20, 30, 40, 50} set1.add(60) print(set1) set1.update([70, 80]) print(set1) set1.remove(30) print(set1) set1.discard(10) print(set1) print(set1.pop(),"is removed!") set1.clear() print(set1)
字典
Python 字典 是鍵值對的集合,並用花括號編寫。
建立字典
my_dict = {'name': 'Kelly Hu', 'age': 27} print(my_dict)
建立空字典
my_dict = {} print(my_dict)
建立具有混合鍵的字典
my_dict = {1: 'Kelly', 'hair_color': 'Brown', (36, 24): 'lucky_numbers'} print(my_dict)
訪問值
你可以透過在方括號內提供用引號括起來的鍵名來直接訪問指定鍵的值,還可以使用 dict.get() 方法 獲取指定鍵的值。
person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'} # Direct access print(person['name']) print(person['age']) print(person['city']) # Using method print(person.get('name')) print(person.get('age')) print(person.get('city'))
修改字典
你可以直接更新現有鍵的值,也可以使用 dict.update() 方法 更新多個值。
person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'} print(person) # Updating single value person['age'] = 18 print(person) # Updating multiple values person.update({'age': 21, 'city': 'New York'}) print(person)
刪除元素
以下方法可用於從字典中刪除元素:
- pop() − 刪除鍵值對並返回值。removed_value = person.pop('age')
- popitem(): 刪除最後新增的項並返回鍵值對。
removed_value = person.popitem() - dict.clear(): 刪除所有項並清空字典。person.clear()
遍歷字典
person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'} # Iterate through keys for key in person: print(key) # Iterate through values for value in person.values(): print(value) # Iterate through key-value pairs for key, value in person.items(): print(f"{key}: {value}")
字典推導式
dict1 = {x: x**2 for x in range(5)} print(dict1)
Lambda 函式
**Python lambda 函式** 只能有一個表示式。它們是小的匿名函式,可以接受任意數量的引數。
value = lambda x : x * 3 print(value(5))
類和物件
Python 是一種面向物件的程式語言,允許建立類和物件。你可以使用“class”關鍵字在 Python 中建立類。
class Person: def __init__(self, name, age): self.name = name self.age = age def display_info(self): print(f"Name: {self.name}, Age: {self.age}") # Create objects per1 = Person("Kelly Hu", 27) per2 = Person("Adele", 25) # Access object attributes print(per1.name) print(per1.age) # Printing using method per2.display_info()
繼承
Python 繼承 允許你將父類的屬性繼承給子類。
基本繼承示例
# Base class class Student: def __init__(self, name, grade): self.name = name self.grade = grade def get_details(self): return f"Student: {self.name}, Grade: {self.grade}" # Derived class class Graduate(Student): def get_details(self): return f"Graduate: {self.name}, Grade: {self.grade}, Status: Graduated" # Create an instance of the child class grad = Graduate("Kelly Hu", "B+") # Access inherited and overridden methods print(grad.get_details())
使用 super() 方法覆蓋方法
super() 方法 用於呼叫父類(或基類)中的方法。
# Base class class Student: def __init__(self, name, grade): self.name = name self.grade = grade def get_details(self): return f"Student: {self.name}, Grade: {self.grade}" # Derived class class Graduate(Student): def __init__(self, name, grade, graduation_year): # Call the parent class's constructor using super() super().__init__(name, grade) self.graduation_year = graduation_year def get_details(self): # Call the parent class's get_details() method using super() student_details = super().get_details() return f"{student_details}, Graduation Year: {self.graduation_year}" # Create an instance of the child class (Graduate) grad = Graduate("Kelly Hu", "B+", 2011) # Access inherited and overridden methods print(grad.get_details())
異常處理
Python 異常處理允許在程式執行期間處理異常。以下關鍵字(塊)用於異常處理:
- **try** − 在要測試異常的主程式碼中編寫。
- **except** − 編寫處理異常的程式碼。
- **else** − 當沒有錯誤時編寫要執行的程式碼。
- **finally** − 無論是否有錯誤,都要編寫最終執行的程式碼。
# Create function to divide two numbers def divide_numbers(a, b): try: result = a / b except ZeroDivisionError: print("Error: Cannot divide by zero!") else: print(f"The divide result is : {result}") finally: print("Execution complete.") # Calling function print("Test Case 1:") divide_numbers(10, 2) print("\nTest Case 2:") divide_numbers(10, 0)