Python 基本概念
本文講解了 Python 的基本概念。
YouTube Video
運行 "Hello World!"
1print("Hello World!")Python 中的變數
在 Python 中,變數是具有名稱的存儲空間,用於在程式中保存及使用數據和信息。變數可以存放各種數據型別,並根據需要重新賦值。下面,我們提供幾個範例程式碼來演示 Python 中變數的基本用法。
1# 1. Assigning values to variables
2# Integer type variable
3age = 25
4print("Age:", age) # Output: Age: 25
5
6# Floating-point type variable
7height = 175.5
8print("Height:", height, "cm") # Output: Height: 175.5 cm
9
10# String type variable
11name = "John"
12print("Name:", name) # Output: Name: John
13
14# Boolean type variable
15is_student = True
16print("Are you a student?", is_student) # Output: Are you a student? True
17
18# 2. Assigning values to multiple variables simultaneously
19# You can assign multiple variables at once
20x, y, z = 5, 10, 15
21print("x =", x, ", y =", y, ", z =", z) # Output: x = 5 , y = 10 , z = 15
22
23# 3. Updating the value of a variable
24# The value of a variable can be updated by reassignment
25age = 26
26print("Updated age:", age) # Output: Updated age: 26
27
28# 4. Updating multiple variables at once
29# Example of swapping values between variables
30a, b = 1, 2
31a, b = b, a
32print("a =", a, ", b =", b) # Output: a = 2 , b = 1
33
34# 5. Type conversion
35# Type conversion allows operations between different types
36count = "5" # String "5"
37count = int(count) # Convert to integer type
38print("Handling count as an integer:", count * 2) # Output: Handling count as an integer: 10
39
40# Conversion to floating-point number
41pi_approx = "3.14"
42pi_approx = float(pi_approx)
43print("Approximation of pi:", pi_approx) # Output: Approximation of pi: 3.14如上所示,Python 中的變數可以靈活使用。變數可以不用指定型別進行使用,並且可以根據需要重新賦予值。此外,型別轉換可以讓不同數據型別之間輕鬆切換。
Python 中的數據型別
Python 有一些基本的數據型別。下面,我們將對每一種進行說明並提供範例程式碼。
整數型別
整數型別用於處理不帶小數點的整數。
1# Example of integer type
2x = 10
3print(x) # Output: 10
4print(type(x)) # Output: <class 'int'>浮點數型別
浮點數型別用於處理帶小數點的數字。
1# Floating Point Number Example
2y = 3.14
3print(y) # Output: 3.14
4print(type(y)) # Output: float字串型別
字串類型表示一系列字符的序列。字串可以用單引號 ' 或雙引號 " 括住。
1# Example of String
2s = "Hello, World!"
3print(s) # Output: Hello, World!
4print(type(s)) # Output: <class 'str'>布林類型
布林類型只有兩個值: true(True)和 false(False)。
1# Example of Boolean
2b = True
3print(b) # Output: True
4print(type(b)) # Output: <class 'bool'>清單類型
清單類型是一個可變的序列,可以存儲多個元素,且這些元素可以是不同的資料類型。
1# Example of List
2lst = [1, 2, 3, "four", 5.0]
3print(lst) # Output: [1, 2, 3, 'four', 5.0]
4print(type(lst)) # Output: <class 'list'>元組類型
元組是一種可以包含多個元素的序列,一旦創建,其內容不可更改。
1# Example of Tuple
2tup = (1, "two", 3.0)
3print(tup) # Output: (1, 'two', 3.0)
4print(type(tup)) # Output: <class 'tuple'>字典類型
字典類型是一種存儲鍵-值對的集合。鍵必須是唯一的。
1# Example of Dictionary
2dct = {"one": 1, "two": 2, "three": 3}
3print(dct) # Output: {'one': 1, 'two': 2, 'three': 3}
4print(type(dct)) # Output: <class 'dict'>集合類型
集合類型是一種存儲唯一元素的集合。不能包含重複的值。
1# Example of Set
2st = {1, 2, 2, 3}
3print(st) # Output: {1, 2, 3}
4print(type(st)) # Output: <class 'set'>這些資料類型是 Python 中處理資料時常用的基本類型。通過適當使用這些類型,您可以滿足程式中的各種需求。
Python 概述
Python 是由 Guido van Rossum 於 1991 年開發的高級程式語言。其設計理念強調「簡單」、「清晰」和「可讀性」,使得代碼直觀、易於編寫且易於閱讀。以下是 Python 的主要特徵概述。
-
易於閱讀且簡單:
- 具有清晰的結構與接近自然語言的表達方式,是初學者容易學習的語言。
- 代碼區塊通過縮排來定義,這自動格式化代碼並提高可讀性。
-
豐富的程式庫與框架:
- 它擁有豐富的標準庫,能夠輕鬆完成許多任務。
- 針對不同領域有專門的庫和框架,例如數值計算(NumPy)、數據分析(Pandas)、機器學習(scikit-learn、TensorFlow)以及網頁開發(Django、Flask)。
-
多功能性:
- Python 既適合作為腳本語言,也適合進行功能完備的應用程序開發。它被廣泛應用於網頁應用程序、桌面應用程序、科學計算、機器學習、數據分析和物聯網等領域。
-
跨平台:
- 它獨立於平台,可以在多種操作系統上運行,包括 Windows、macOS 和 Linux。
-
開源與社群:
- Python 是一個開源項目,並由一個活躍的社群支持。因此,它提供了頻繁的更新、庫的開發及支持。
-
動態類型與自動內存管理:
- 動態類型消除了聲明變量類型的需求,加速了開發過程。
- 垃圾回收機制執行自動內存管理,使內存管理變得簡單。
憑藉這些特性,Python 被廣泛應用於教育、工業和學術等多個領域。
Python 中的轉義字符
在 Python 中,轉義字符用來在字符串中加入特定的控制字符或具有特殊含義的字符。轉義字符是用於為普通字符串添加特定含義的特殊符號。讓我們深入了解一下 Python 中的轉義字符。
轉義字符的基礎
在 Python 中,轉義字符通過反斜杠 (\) 定義。轉義字符用於在普通字符串中表示特定行為。例如,\n 代表換行,\t 代表製表符。
您可以使用以下方式定義包含轉義字符的字符串:。
1# Example of escape characters
2print("Hello\nWorld") # A newline is inserted after "Hello"
3
4# Output:
5# Hello
6# World主要轉義字符列表
Python 中使用的主要轉義字符如下:。
\\: 表示一個反斜杠本身。\': 在字符串中包含單引號。\": 在字符串中包含雙引號。\n: 換行\t: 製表符\r: 回車\b: 退格\f: 換頁\a:提示聲(鈴聲)\v: 垂直製表符\N{name}: 使用 Unicode 資料庫中的名稱指定的字符\uXXXX: 16 位的 Unicode 字符(用 4 個十六進制數字表示)\UXXXXXXXX: 32 位的 Unicode 字符(用 8 個十六進制數字表示)\xXX: 使用十六進制指定的字符
常用的轉義字符示例
以下是一些如何使用轉義字符的具體示例。
雙引號和單引號
在字符串中包含雙引號或單引號時,使用轉義字符。
1# String containing double quotes
2quote = "He said, \"Python is amazing!\""
3print(quote)
4
5# String containing single quotes
6single_quote = 'It\'s a beautiful day!'
7print(single_quote)
8
9# Output:
10# He said, "Python is amazing!"
11# It's a beautiful day!換行和製表符
換行和製表符通常用於格式化文本。
1# Example using newline
2multiline_text = "First line\nSecond line"
3print(multiline_text)
4
5# Example using tab
6tabbed_text = "Column1\tColumn2\tColumn3"
7print(tabbed_text)
8
9# Output:
10# First line
11# Second line
12# Column1 Column2 Column3Unicode轉義字符
在Python中,Unicode字符使用\u或\U表示。這在處理非英文字符時特別有用。
1# Example of Unicode escape
2japanese_text = "\u3053\u3093\u306B\u3061\u306F" # Hello in Japanese
3print(japanese_text)
4# Output:
5# こんにちは(Hello in Japanese)使用特殊轉義字符時的注意事項
使用轉義字符時需要記住一些注意事項。
- 【原始字串】:如果您想要如實顯示包含反斜線(\)的字串,請在字串前加上
r。
1raw_string = r"C:\Users\name\Documents"
2print(raw_string)
3# Output:
4# C:\Users\name\Documents在原始字符串中,反斜杠不會被解釋為轉義字符,而是按原樣輸出。
- 使用Unicode:在使用Unicode轉義字符時,請確保指定的十六進制代碼正確。錯誤的代碼會導致字符顯示錯誤。
轉義反斜杠
在字符串中包含反斜杠本身時,使用雙反斜杠。
1# Example containing backslash
2path = "C:\\Program Files\\Python"
3print(path)
4# Output:
5# C:\Program Files\Python高級示例:複雜字符串格式化
還可以結合使用轉義字符來格式化複雜字符串。
1# Example of formatting a message
2message = "Dear User,\n\n\tThank you for your inquiry.\n\tWe will get back to you shortly.\n\nBest Regards,\nCustomer Support"
3print(message)
4# Output:
5# Dear User,
6#
7# Thank you for your inquiry.
8# We will get back to you shortly.
9#
10# Best Regards,
11# Customer Support總結
Python的轉義字符是用於在字符串中包含特定控制字符或特殊字符的強大工具。了解如何使用並根據需要適當應用它們,可以實現更靈活的字符串處理。
Python 版本
讓我們簡要回顧一下主要的 Python 發布版本及其特性。
- Python 1.0(1994 年)
1# Sample code that works in Python 1.0
2def greet(name):
3 print "Hello, " + name # print was a statement
4
5greet("World")首次正式發佈。Python 的基本語法和標準庫得以建立。
- Python 2.0(2000 年)
1# Sample code that works in Python 2.0
2
3# List comprehension
4squares = [x * x for x in range(5)]
5print squares
6
7# Unicode string (u"...")
8greet = u"Hello"
9print greet新增了諸如列表解析、完整垃圾回收以及對 Unicode 支持的開始等重要功能。Python 2 被長期使用,但於 2020 年結束支持。
- Python 3.0(2008 年)
1# Sample code that works in Python 3.0
2
3# print is now a function
4print("Hello, world!")
5
6# Unicode text is handled natively
7message = "Hello"
8print(message)一次重大更新,不具向後兼容性。print 被改為函數,Unicode 成為默認的字符串類型,整數類型被統一,大大提升了 Python 的一致性和可用性。Python 3 是目前的主流版本。
- Python 3.5(2015)
1# Sample code that works in Python 3.5
2import asyncio
3
4async def say_hello():
5 await asyncio.sleep(1)
6 print("Hello, async world!")
7
8asyncio.run(say_hello())引入了 async/await 語法,使編寫非同步程式更加簡單。
- Python 3.6(2016)
1# Sample code that works in Python 3.6
2
3name = "Alice"
4age = 30
5print(f"{name} is {age} years old.") # f-string makes formatting simple新增了 格式化字串文本 (f-strings),使字串格式化更加方便。此外,型別提示 (type hints) 得到了擴展。
- Python 3.7(2018)
1# Sample code that works in Python 3.7
2
3from dataclasses import dataclass
4
5@dataclass
6class Person:
7 name: str
8 age: int
9
10p = Person("Bob", 25)
11print(p)引入了 Dataclasses,使定義類似結構的類別更加容易。對 async/await 的支援也得到了加強。
- Python 3.8(2019)
1# Sample code that works in Python 3.8
2
3# Assignment inside an expression
4if (n := len("hello")) > 3:
5 print(f"Length is {n}")新增了 海象運算符 (:=),允許使用賦值表達式。引入了僅位置參數 (Positional-only parameters),提高了函式參數的靈活性。
- Python 3.9(2020)
1# Sample code that works in Python 3.9
2
3a = {"x": 1}
4b = {"y": 2}
5c = a | b # merge two dicts
6print(c) # {'x': 1, 'y': 2}改進了型別提示,並新增了用於列表和字典的合併運算符 (|)。標準函式庫也進行了重組。
- Python 3.10(2021)
1# Sample code that works in Python 3.10
2
3def handle(value):
4 match value:
5 case 1:
6 return "One"
7 case 2:
8 return "Two"
9 case _:
10 return "Other"
11
12print(handle(2))新增了 模式匹配 (Pattern matching),使條件語句更加強大。錯誤訊息得到了改進,型別系統進一步加強。
- Python 3.11(2022)
1# Sample code that works in Python 3.11
2
3# Improved performance (up to 25% faster in general)
4# More informative error messages
5try:
6 eval("1/0")
7except ZeroDivisionError as e:
8 print(f"Caught an error: {e}")進行了 **顯著的性能改進**,使執行速度相比之前版本更快。此外,對異常處理和型別檢查進行了改進。
- Python 3.12(2023)
1# Sample code that works in Python 3.12
2
3# Automatically shows exception chains with detailed traceback
4def f():
5 raise ValueError("Something went wrong")
6
7def g():
8 try:
9 f()
10 except Exception:
11 raise RuntimeError("Higher level error") # Automatically chained
12
13try:
14 g()
15except Exception as e:
16 import traceback
17 traceback.print_exception(type(e), e, e.__traceback__)錯誤訊息進一步改進,並增強了性能。此外,自動顯示異常鏈接,有助於更詳細的除錯。新增了新語法功能並增強了標準函式庫,提高了開發者的生產力。
- Python 3.13(2024)
1# Sample code that works in Python 3.13
2
3# Using the new 'except*' syntax for handling multiple exceptions in parallel
4import asyncio
5
6async def raise_errors():
7 raise ExceptionGroup("Multiple errors", [
8 ValueError("Invalid value"),
9 TypeError("Wrong type"),
10 ])
11
12async def main():
13 try:
14 await raise_errors()
15 except* ValueError as e:
16 print("Caught ValueError(s):", e.exceptions)
17 except* TypeError as e:
18 print("Caught TypeError(s):", e.exceptions)
19
20asyncio.run(main())在 Python 3.13 中,ExceptionGroup 和 except* 語法得到了進一步完善,允許在非同步處理中並行捕捉多個異常。這使得在使用平行處理或 asyncio 的應用程式中,除錯與錯誤處理變得更加直觀且強大。此外,型別提示(type hints)的改進和標準程式庫的更新提升了程式的可維護性與表達能力。
Python 3 版本持續發展,最新版本包含效能提升、型別系統改進以及新增功能。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。