作为一门简洁高效的编程语言,Python凭借其丰富的内置函数(Built-in Functions)深受开发者喜爱。本文整理了50个必须掌握的Python基础函数,通过分类解析+代码实例助您快速上手。
一、输入输出函数
1. print()
输出内容到控制台
print("Hello World!") # 输出字符串 print(3*7, end=' ') # 输出21并修改换行结尾符
2. input()
获取用户输入
name = input("请输入姓名:") print(f"欢迎{name}!")
二、类型转换
3. int()
转换为整数类型
num = int("42") # 字符串转整型 → 42
4. float()
转换为浮点数
pi = float("3.1415") # → 3.1415
5. str()
转字符串类型
version = str(3.11) # → '3.11'
(持续列举type()/bool()/list()/tuple()/set()/dict()等转换函数)
三、数学运算
11. abs()
求绝对值
print(abs(-10)) # 输出10
12. round()
四舍五入
print(round(3.14159, 2)) # →3.14
(包含max()/min()/sum()/divmod()等数学相关函数)
四、序列操作
17. len()
获取元素个数
lst = [1,2,3] print(len(lst)) # 输出3
18. sorted()
返回排序新列表
nums = [3,1,4] print(sorted(nums)) # →[1,3,4]
(涵盖reversed()/enumerate()/zip()/range()等迭代工具)
五、函数式编程
28. map()
应用函数到可迭代对象
numbers = [1,2,3] squared = map(lambda x:x**2, numbers) print(list(squared)) # [1,4,9]
29. filter()
过滤元素
nums = [5,12,8,19] print(list(filter(lambda x:x>10, nums))) # [12,19]
六、对象属性
35. isinstance()
类型检查
print(isinstance(5, int)) # True
36. id()
获取对象内存地址
a = [] print(id(a)) # 输出类似140230370848
七、文件操作
40. open()
打开文件
with open('data.txt', 'r') as f: content = f.read()
八、其他实用工具
45. help()
查看帮助文档
help(print) # 显示print函数文档
46. dir()
查看对象属性
print(dir(str)) # 显示字符串方法
完整50函数速查表
分类 | 函数列表 |
---|---|
输入输出 | print/input |
类型转换 | int/float/str/list... |
数学计算 | abs/round/sum... |
序列处理 | len/sorted/enumerate... |
高阶函数 | map/filter/zip... |
对象操作 | type/id/isinstance... |
系统交互 | open/exit... |
使用建议
1️⃣ 善用help()函数实时查询用法
2️⃣ 组合使用函数实现复杂逻辑(如map+lambda)
3️⃣ 注意类型转换时数据有效性