Python 資料型別 (Data Types)
Python 有多種內建的資料型別,用來儲存不同類型的資料。
基本資料型別
| 類型 | 說明 | 範例 |
|---|---|---|
int | 整數 | 10, -5, 0 |
float | 浮點數(小數) | 3.14, -0.5, 2.0 |
str | 字串 | "Hello", 'Python' |
bool | 布林值 | True, False |
None | 空值 | None |
# 整數
age = 25
# 浮點數
price = 99.5
# 字串
name = "Alice"
# 布林值
is_active = True
# 空值
result = None
複合資料型別
| 類型 | 說明 | 範例 |
|---|---|---|
list | 串列(可變、有序) | [1, 2, 3] |
tuple | 元組(不可變、有序) | (1, 2, 3) |
dict | 字典(鍵值對) | {"name": "Alice", "age": 25} |
set | 集合(不重複元素) | {1, 2, 3} |
# 串列
fruits = ["apple", "banana", "orange"]
# 元組
coordinates = (10, 20)
# 字典
person = {"name": "Alice", "age": 25}
# 集合
numbers = {1, 2, 3, 4, 5}
查看資料型別
使用 type() 函數可以查看變數的資料型別:
print(type(25)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({"a": 1})) # <class 'dict'>
print(type({1, 2, 3})) # <class 'set'>
型別檢查
使用 isinstance() 函數可以檢查變數是否為特定型別:
x = 10
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
print(isinstance(x, str)) # False
# 可以檢查多個型別
print(isinstance(x, (int, float))) # True
可變與不可變型別
Python 的資料型別分為可變(mutable)和不可變(immutable):
不可變型別:建立後內容不能修改
int,float,str,bool,tuple,None
可變型別:建立後內容可以修改
list,dict,set
# 不可變 - 字串
name = "Alice"
# name[0] = "B" # TypeError! 字串不能修改
# 可變 - 串列
fruits = ["apple", "banana"]
fruits[0] = "orange" # OK! 串列可以修改
print(fruits) # ['orange', 'banana']
理解可變與不可變型別對於避免程式中的意外行為非常重要,特別是在函數傳遞參數時。