02 - 基本資料型態(Data Types)

01-什麼是Python | 下一篇 → 03-控制流程


變數(Variable)

# 直接賦值,不需要宣告型別
name = "DirtyWolf"    # 字串
age = 25              # 整數
height = 1.75         # 浮點數
is_doctor = True      # 布林值
 
# 查看型別
print(type(name))    # <class 'str'>

數字型態

int(整數)

x = 10
y = -3
z = 1_000_000    # 底線可提高可讀性
 
# 運算
print(10 + 3)    # 13
print(10 - 3)    # 7
print(10 * 3)    # 30
print(10 / 3)    # 3.3333...(浮點除法)
print(10 // 3)   # 3(整數除法)
print(10 % 3)    # 1(餘數)
print(2 ** 10)   # 1024(次方)

float(浮點數)

pi = 3.14159
e = 2.71828
 
# 四捨五入
round(3.14159, 2)    # 3.14

字串(str)

s1 = "Hello"
s2 = 'World'
s3 = """多行
字串"""
 
# 常用操作
print(len(s1))           # 5(長度)
print(s1.upper())        # HELLO
print(s1.lower())        # hello
print(s1 + " " + s2)    # Hello World(串接)
print(s1 * 3)            # HelloHelloHello(重複)
print(s1[0])             # H(索引)
print(s1[1:3])           # el(切片)
 
# f-string(格式化,Python 3.6+,推薦)
name = "Andrew"
age = 28
print(f"我叫 {name},今年 {age} 歲")

布林(bool)

is_valid = True
is_empty = False
 
# 比較運算
print(5 > 3)     # True
print(5 == 5)    # True
print(5 != 3)    # True
 
# 邏輯運算
print(True and False)    # False
print(True or False)     # True
print(not True)          # False

串列(list)

有序、可修改的集合:

fruits = ["apple", "banana", "cherry"]
 
# 存取
print(fruits[0])     # apple
print(fruits[-1])    # cherry(最後一個)
 
# 修改
fruits.append("mango")      # 新增到末尾
fruits.insert(1, "grape")   # 插入到指定位置
fruits.remove("banana")     # 刪除指定值
fruits.pop()                # 刪除最後一個
 
# 切片
print(fruits[1:3])   # 取第 2 到第 3 個元素
 
# 長度
print(len(fruits))

字典(dict)

Key-Value 對的集合:

person = {
    "name": "Andrew",
    "age": 28,
    "job": "doctor"
}
 
# 存取
print(person["name"])         # Andrew
print(person.get("age"))      # 28(推薦,不會報錯)
 
# 修改/新增
person["age"] = 29
person["city"] = "Taipei"
 
# 刪除
del person["job"]
 
# 遍歷
for key, value in person.items():
    print(f"{key}: {value}")

元組(tuple)

有序、不可修改的集合:

coordinates = (25.05, 121.53)
print(coordinates[0])    # 25.05
 
# 常見用途:函式回傳多個值
def get_size():
    return 1920, 1080    # 其實是 tuple
 
width, height = get_size()

集合(set)

不重複元素的集合:

tags = {"python", "coding", "python"}    # 重複會自動去掉
print(tags)    # {'python', 'coding'}
 
tags.add("obsidian")
tags.discard("coding")

型別轉換

int("42")        # str → int:42
float("3.14")    # str → float:3.14
str(100)         # int → str:"100"
list("hello")    # str → list:['h', 'e', 'l', 'l', 'o']

01-什麼是Python | 下一篇 → 03-控制流程