Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
float():浮點數轉換
語法:
float(x)把值轉換成浮點數(小數)。可以接受整數、字串,甚至特殊值:print(float(10)) # 10.0
print(float("3.14")) # 3.14
print(float("-2.5")) # -2.5
print(float("inf")) # inf(無限大)
print(float("-inf")) # -inf(負無限大)
print(float("nan")) # nan(不是數字)不帶參數呼叫會回傳 0.0:
print(float()) # 0.0注意浮點數精度問題,這是所有程式語言都有的:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False!
# 正確的比較方式
print(abs(0.1 + 0.2 - 0.3) < 1e-9) # True不能轉換的字串會報錯:
# float("hello") # ValueError: could not convert string to float: 'hello'小小綜合例子
# 計算平均成績(整數除法 vs 浮點數除法)
scores = [85, 92, 78, 90, 88]
total = sum(scores)
# 用 float 確保精確除法
avg = float(total) / len(scores)
print(f"平均分:{avg}") # 平均分:86.6
# 安全轉換使用者輸入
user_input = "42.5"
try:
value = float(user_input)
print(f"轉換成功:{value}")
except ValueError:
print("請輸入有效的數字")
# 判斷特殊浮點數
import math
x = float("inf")
print(math.isinf(x)) # True
print(math.isnan(float("nan"))) # True












