← 從零開始學 Python
第 8 課,共 78 課 · 10 XP
什麼是資料型別?
理論與題目說明
機器翻譯,尚未經母語人士審閱。
Python 裡的每個值都有資料型別(型別),型別決定了這個值能做什麼。type() 會告訴你型別:
type(5) # <class 'int'> —— 整數
type(2.5) # <class 'float'> —— 浮點數
type("文字") # <class 'str'> —— 字串
type(True) # <class 'bool'> —— 布林值
type([1, 2]) # <class 'list'> —— 串列
type(None) # <class 'NoneType'>
型別很重要,因為同一個運算在不同型別上的行為不一樣:
print(2 + 3) # 5
print("2" + "3") # 23 —— 字串會接在一起
print(2 + "3") # TypeError:數字和字串不能相加
只想要型別的名字時:type(5).__name__ → 'int'。
題目。 寫一個函式 kind(x),以字串回傳值的型別名稱:kind(5) → 'int',kind("a") → 'str'。