Python 基本語法: 入門篇
Python 以其簡潔、易讀的語法而聞名,非常適合初學者入門。
1. 變數 (Variables)
在 Python 中,你不需要預先宣告變數的類型,可以直接賦值。Python 會根據你賦予的值自動判斷變數的類型。
- 賦值: 使用
=
運算符。 - 命名規則:
- 可以包含字母、數字和底線
_
。 - 必須以字母或底線開頭。
- 不能以數字開頭。
- 大小寫敏感 (
name
和Name
是不同的變數)。 - 不能使用 Python 的關鍵字 (如
if
,for
,class
等)。 - 推薦使用小寫字母和底線來命名變數 (e.g.,
my_variable
)。
- 可以包含字母、數字和底線
Python
# 變數賦值範例
name = "Alice" # 字串 (string)
age = 30 # 整數 (integer)
height = 1.75 # 浮點數 (float)
is_student = True # 布林值 (boolean)
# 打印變數值
print(name) # 輸出: Alice
print(age) # 輸出: 30
print(height) # 輸出: 1.75
print(is_student) # 輸出: True
# 可以隨時改變變數的值和類型 (動態類型語言特性)
age = "thirty"
print(age) # 輸出: thirty
2. 數據類型 (Data Types)
Python 擁有多種內建數據類型,可以儲存不同種類的數據。
a. 整數 (int) 和 浮點數 (float)
- int: 用於儲存整數。
- float: 用於儲存帶小數點的數值。
Python
num_int = 10
num_float = 3.14159
print(type(num_int)) # 輸出: <class 'int'>
print(type(num_float)) # 輸出: <class 'float'>
# 算術運算
print(5 + 2) # 加法: 7
print(5 - 2) # 減法: 3
print(5 * 2) # 乘法: 10
print(5 / 2) # 除法 (結果為浮點數): 2.5
print(5 // 2) # 整數除法 (結果為整數,向下取整): 2
print(5 % 2) # 取餘數: 1
print(5 ** 2) # 冪運算: 25
b. 字串 (str)
用於儲存文字資料。可以使用單引號 ' '
或雙引號 " "
定義。
Python
greeting = "Hello, Python!"
name = 'Bob'
print(greeting) # 輸出: Hello, Python!
print(name) # 輸出: Bob
# 字串連接
full_message = greeting + " My name is " + name
print(full_message) # 輸出: Hello, Python! My name is Bob
# 字串格式化 (f-strings, Python 3.6+ 推薦)
age = 25
formatted_message = f"My name is {name} and I am {age} years old."
print(formatted_message) # 輸出: My name is Bob and I am 25 years old.
# 字串長度
print(len(greeting)) # 輸出: 14
# 字串索引 (從 0 開始) 和切片
print(greeting[0]) # 輸出: H
print(greeting[7:13]) # 輸出: Python
c. 布林值 (bool)
只有兩個值:True
和 False
(首字母大寫)。常用於條件判斷。
Python
is_active = True
is_empty = False
print(is_active) # 輸出: True
print(is_empty) # 輸出: False
# 比較運算符返回布林值
print(10 > 5) # 輸出: True
print(10 == 5) # 輸出: False
print(10 != 5) # 輸出: True
d. 列表 (list)
有序、可變 (mutable) 的集合,可以儲存任何類型的數據。用方括號 []
定義。
Python
my_list = [1, "apple", 3.14, True]
print(my_list) # 輸出: [1, 'apple', 3.14, True]
# 訪問元素 (索引從 0 開始)
print(my_list[1]) # 輸出: apple
# 修改元素
my_list[0] = 100
print(my_list) # 輸出: [100, 'apple', 3.14, True]
# 添加元素
my_list.append("banana") # 在末尾添加
print(my_list) # 輸出: [100, 'apple', 3.14, True, 'banana']
# 插入元素
my_list.insert(1, "orange") # 在指定位置插入
print(my_list) # 輸出: [100, 'orange', 'apple', 3.14, True, 'banana']
# 刪除元素
my_list.remove("apple") # 移除第一個匹配的值
print(my_list) # 輸出: [100, 'orange', 3.14, True, 'banana']
# 列表長度
print(len(my_list)) # 輸出: 5
# 列表切片
print(my_list[1:4]) # 輸出: ['orange', 3.14, True]
e. 元組 (tuple)
有序、不可變 (immutable) 的集合,可以儲存任何類型的數據。用圓括號 ()
定義。
Python
my_tuple = (1, "apple", 3.14)
print(my_tuple) # 輸出: (1, 'apple', 3.14)
# 訪問元素 (與列表相同)
print(my_tuple[1]) # 輸出: apple
# 注意:元組一旦創建就不能修改、添加或刪除元素
# my_tuple[0] = 100 # 這會導致錯誤: TypeError: 'tuple' object does not support item assignment
# 元組長度
print(len(my_tuple)) # 輸出: 3
f. 字典 (dict)
無序、可變的鍵值對 (key-value pairs) 集合。用花括號 {}
定義。鍵必須是唯一的且不可變(如字串、數字、元組)。
Python
my_dict = {
"name": "Charlie",
"age": 28,
"city": "New York"
}
print(my_dict) # 輸出: {'name': 'Charlie', 'age': 28, 'city': 'New York'}
# 訪問值 (透過鍵)
print(my_dict["name"]) # 輸出: Charlie
# 添加/修改鍵值對
my_dict["email"] = "charlie@example.com"
my_dict["age"] = 29
print(my_dict) # 輸出: {'name': 'Charlie', 'age': 29, 'city': 'New York', 'email': 'charlie@example.com'}
# 刪除鍵值對
del my_dict["city"]
print(my_dict) # 輸出: {'name': 'Charlie', 'age': 29, 'email': 'charlie@example.com'}
# 字典的鍵、值、項目
print(my_dict.keys()) # 輸出: dict_keys(['name', 'age', 'email'])
print(my_dict.values()) # 輸出: dict_values(['Charlie', 29, 'charlie@example.com'])
print(my_dict.items()) # 輸出: dict_items([('name', 'Charlie'), ('age', 29), ('email', 'charlie@example.com')])
g. 集合 (set)
無序、可變的元素集合,不允許重複元素。用花括號 {}
定義,或使用 set()
函數。
Python
my_set = {1, 2, 3, 2, 1} # 重複元素會被自動移除
print(my_set) # 輸出: {1, 2, 3} (順序可能不同)
# 從列表創建集合
another_set = set([4, 5, 5, 6])
print(another_set) # 輸出: {4, 5, 6}
# 添加元素
my_set.add(4)
print(my_set) # 輸出: {1, 2, 3, 4}
# 移除元素
my_set.remove(2)
print(my_set) # 輸出: {1, 3, 4}
# 集合運算 (聯集、交集、差集)
set_a = {1, 2, 3}
set_b = {3, 4, 5}
print(set_a.union(set_b)) # 聯集: {1, 2, 3, 4, 5}
print(set_a.intersection(set_b)) # 交集: {3}
print(set_a.difference(set_b)) # 差集 (在 A 但不在 B): {1, 2}
3. 控制流 (Control Flow)
控制流語句允許你根據條件執行不同的程式碼塊,或重複執行某個程式碼塊。
a. if
/elif
/else
語句 (條件判斷)
用於根據條件執行不同的程式碼。Python 使用縮排 (Indentation) 來定義程式碼塊,而不是大括號 {}
。
Python
score = 85
if score >= 90:
print("優秀")
elif score >= 70:
print("良好")
else:
print("及格")
# 輸出: 良好
# 注意:Python 沒有 switch 語句,通常用 if/elif/else 替代或使用字典映射。
b. for
迴圈 (遍歷)
用於遍歷序列 (如列表、元組、字串) 或其他可迭代對象。
Python
# 遍歷列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 輸出:
# apple
# banana
# cherry
# 遍歷字串
for char in "Python":
print(char)
# 輸出: P y t h o n (每個字元一行)
# 遍歷數字範圍 (使用 range() 函數)
# range(n) 生成從 0 到 n-1 的序列
# range(start, end) 生成從 start 到 end-1 的序列
# range(start, end, step) 生成從 start 到 end-1,步長為 step 的序列
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# 輸出: 0 1 2 3 4
for i in range(1, 4): # 1, 2, 3
print(i)
# 遍歷字典
my_dict = {"name": "David", "age": 40}
for key in my_dict: # 預設遍歷鍵
print(f"Key: {key}, Value: {my_dict[key]}")
for value in my_dict.values(): # 遍歷值
print(f"Value: {value}")
for key, value in my_dict.items(): # 同時遍歷鍵和值
print(f"Key: {key}, Value: {value}")
# break 和 continue
for i in range(10):
if i == 3:
continue # 跳過當前迭代,繼續下一個
if i == 7:
break # 終止整個迴圈
print(i)
# 輸出: 0 1 2 4 5 6
c. while
迴圈 (條件重複)
只要指定條件為真,就會一直重複執行程式碼塊。
Python
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # 等同於 count = count + 1
# 輸出:
# Count is: 0
# Count is: 1
# Count is: 2
# Count is: 3
# Count is: 4
# 無限迴圈 (需要搭配 break)
# while True:
# user_input = input("Enter 'quit' to exit: ")
# if user_input == 'quit':
# break
# print(f"You entered: {user_input}")
4. 函數 (Functions)
函數是可重複使用的程式碼塊,用於執行特定任務。它有助於組織程式碼、提高可讀性和減少重複。
- 定義函數: 使用
def
關鍵字。 - 參數: 函數可以接受輸入參數。
- 返回值: 使用
return
語句返回結果。
Python
# 定義一個簡單的函數
def greet():
print("Hello, welcome to Python!")
# 呼叫函數
greet() # 輸出: Hello, welcome to Python!
# 帶參數的函數
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Eve") # 輸出: Hello, Eve!
greet_person("Frank")
# 帶多個參數的函數
def add(a, b):
return a + b # 返回兩個數的和
result = add(10, 5)
print(result) # 輸出: 15
# 帶有預設參數的函數
def calculate_area(length, width=10): # width 有預設值
return length * width
print(calculate_area(5)) # 輸出: 50 (使用預設 width=10)
print(calculate_area(5, 20)) # 輸出: 100 (覆蓋預設 width=20)
# 變數參數 (可變數量參數)
def sum_all(*numbers): # *numbers 會將所有傳入的額外參數打包成一個元組
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 輸出: 6
print(sum_all(10, 20, 30, 40)) # 輸出: 100
# 關鍵字參數 (可變數量關鍵字參數)
def print_info(**kwargs): # **kwargs 會將所有傳入的額外關鍵字參數打包成一個字典
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Grace", age=35, city="London")
# 輸出:
# name: Grace
# age: 35
# city: London
這涵蓋了 Python 最基礎且核心的語法概念。掌握這些知識是學習 Python 更進階主題(如物件導向程式設計、模組、文件操作、錯誤處理等)以及數據科學和 AI 庫的基礎。多練習、多寫程式碼是最好的學習方式!
沒有留言:
張貼留言