前言
上一篇提到,input() 拿到的內容永遠是字串,就算使用者打的是數字也一樣:
age = input("請輸入你的年齡:")
print("明年你" + age + 1 + "歲")TypeError: can only concatenate str (not "int") to str要修好這支程式,得靠 Python 內建的型別轉換函式。這篇把 int()、float()、str()、bool() 這四個函式的行為跟常見誤區講清楚。
int():轉整數
int("25") # 25,字串轉整數
int(3.9) # 3,浮點數轉整數是「無條件捨去」,不是四捨五入
int("3.9") # ValueError!int() 不能直接吃帶小數點的字串最後一個是新手很常踩的坑:字串 "3.9" 沒辦法直接用 int() 轉,要先過一手 float():
int(float("3.9")) # 3float():轉浮點數
float("3.14") # 3.14
float(10) # 10.0
float("inf") # inf,特殊值,代表無限大str():轉字串
str(25) # "25"
str(3.14) # "3.14"
str(True) # "True"bool():轉布林值
bool() 的規則不是直覺上的「非空即真」,而是 Python 定義的一套「假值(falsy)」規則——以下這些值轉成 bool 都是 False,其他一律是 True:
bool(0) # False
bool(0.0) # False
bool("") # False,空字串
bool([]) # False,空 list
bool(None) # False
bool(1) # True
bool("0") # True!字串 "0" 不是空字串,所以是 True,這裡最容易搞錯
bool("False") # True!只要字串本身不是空字串,一律 True綜合範例:把 input() 修好
回到開頭那支會噴錯的程式,用今天學到的東西修好它:
age = int(input("請輸入你的年齡:"))
print(f"明年你 {age + 1} 歲")再做一個實用一點的,BMI 計算機,把 input()、float()、f-string 全部用上:
name = input("請輸入姓名:")
height = float(input("請輸入身高(公尺):"))
weight = float(input("請輸入體重(公斤):"))
bmi = weight / (height ** 2)
print(f"{name} 的 BMI 是 {bmi:.1f}")小結
變數不用宣告型態,不代表型態不重要——尤其 input() 永遠回傳字串這件事,是新手最容易忘記的細節。記住 int() / float() / str() / bool() 這四個轉換函式的行為,配合 type() 隨時檢查,寫程式時遇到奇怪的 TypeError 大概就能猜到問題在哪。
這篇對應的是 Python 基礎入門課程 Ch02,如果想搭配完整的課堂教材與練習題,可以到課程頁看看。