資料、資料型態
Python 常見的基礎資料型態如下:
| 資料型態 | 說明 | 範例 |
|---|---|---|
| `int` | 整數 | `10`、`-3` |
| `float` | 浮點數(小數) | `3.14`、`-0.5` |
| `complex` | 複數 | `2 + 3j` |
| `bool` | 布林值,只有 `True` 或 `False` | `True` |
| `str` | 字串 | `"Hello"`、`'Python'` |
| `list` | 有順序、可修改的集合 | `[1, 2, 3]` |
| `tuple` | 有順序、不可修改的集合 | `(1, 2, 3)` |
| `dict` | 字典,以鍵值配對儲存資料 | `{"name": "Amy", "age": 20}` |
| `set` | 無順序且不重複的集合 | `{1, 2, 3}` |
| `NoneType` | 表示沒有值 | `None` |
## 範例一:基本資料型態與型態檢查
```python
age = 20
height = 175.5
name = "小明"
is_student = True
print(age, type(age))
print(height, type(height))
print(name, type(name))
print(is_student, type(is_student))
```
輸出結果會類似:
```text
20 <class 'int'>
175.5 <class 'float'>
小明 <class 'str'>
True <class 'bool'>
```
`type()` 函式可以用來查看變數的資料型態。
## 範例二:使用串列與字典
```python
fruits = ["蘋果", "香蕉", "橘子"]
student = {
"name": "小華",
"age": 18
}
fruits.append("芒果")
print("水果:", fruits)
print("姓名:", student["name"])
print("年齡:", student["age"])
```
輸出:
```text
水果: ['蘋果', '香蕉', '橘子', '芒果']
姓名: 小華
年齡: 18
```
其中,`list` 可以使用 `append()` 新增元素;`dict` 則透過鍵(例如 `"name"`)取得對應的值。
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫