Python內置函數介紹(上)
1. 基礎輸入輸出函數
# print() 函數
print("Hello World") # 基本輸出
print("A", "B", "C", sep="-") # 使用分隔符
print("Line 1", end="->") # 自定義結尾
# input() 函數
name = input("請輸入您的名字:")
age = int(input("請輸入您的年齡:"))
2. 數值相關函數
# abs() - 絕對值
print(abs(-5)) # 5
# round() - 四捨五入
print(round(3.7)) # 4
print(round(3.1415, 2)) # 3.14
# max() 和 min() - 最大值和最小值
print(max(1, 2, 3, 4)) # 4
print(min([1, 2, 3, 4])) # 1
# sum() - 求和
print(sum([1, 2, 3, 4])) # 10
3. 類型轉換函數
# int() - 轉換為整數
print(int("123")) # 123
print(int(12.34)) # 12
# float() - 轉換為浮點數
print(float("12.34")) # 12.34
print(float(12)) # 12.0
# str() - 轉換為字符串
print(str(123)) # "123"
print(str(12.34)) # "12.34"
# bool() - 轉換為布爾值
print(bool(1)) # True
print(bool("")) # False
4. 序列操作函數
# len() - 獲取長度
print(len("Python")) # 6
print(len([1, 2, 3])) # 3
# range() - 生成數字序列
for i in range(5): # 0,1,2,3,4
print(i)
# sorted() - 排序
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers)) # [1, 1, 3, 4, 5]
print(sorted(numbers, reverse=True)) # [5, 4, 3, 1, 1]
# enumerate() - 同時獲取索引和值
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
5. 類型判斷函數
# type() - 獲取對象類型
print(type(123)) #
print(type("hello")) #
# isinstance() - 判斷對象類型
print(isinstance(123, int)) # True
print(isinstance("hello", str)) # True
print(isinstance(123, (int, float))) # True
練習題
-
使用內置函數處理以下任務:
- 計算列表[10, -5, 8, -12, 3]中的最大絕對值
- 將字符串”3.14159″轉換為保留2位小數的浮點數
- 生成1到100中的偶數列表
常見錯誤和注意事項
- 類型轉換時注意數據格式是否合法
- 使用len()函數時注意對象是否可計算長度
- range()函數生成的是一個可迭代對象,不是列表
- sorted()函數不會改變原序列,而是返回新序列
補充資源
- Python官方文檔中的內置函數部分
- 更多內置函數示例和練習
- 常見內置函數的性能比較
- 內置函數的實際應用場景