当前位置:首页 > Python > 正文

Python内置函数完全指南 - 从入门到精通 | Python教程

Python内置函数完全指南

掌握70+个Python内置函数,提升编程效率与代码质量

什么是Python内置函数?

Python内置函数是Python解释器预先定义的函数,无需导入任何模块即可直接使用。它们提供了基础且强大的功能,覆盖数据类型处理、数学运算、对象操作等多个方面。

内置函数的优势

  • 无需导入,开箱即用
  • 经过高度优化,执行效率高
  • 标准化实现,保证代码一致性
  • 跨平台兼容性

使用场景

  • 数据类型转换
  • 集合与序列操作
  • 数学计算
  • 对象属性操作
  • 输入输出处理

常用内置函数详解

len() - 获取长度

返回对象(字符串、列表、元组等)的长度或元素个数。

示例代码:

# 字符串长度
text = "Python"
print(len(text))  # 输出: 6

# 列表元素个数
numbers = [1, 2, 3, 4, 5]
print(len(numbers))  # 输出: 5

# 字典键值对数量
user = {"name": "Alice", "age": 30}
print(len(user))  # 输出: 2

range() - 生成序列

生成一个不可变的数字序列,常用于for循环中。

示例代码:

# 生成0-4的序列
for i in range(5):
    print(i)  # 输出: 0 1 2 3 4

# 生成5-9的序列
for i in range(5, 10):
    print(i)  # 输出: 5 6 7 8 9

# 生成0-10的偶数
even_numbers = list(range(0, 11, 2))
print(even_numbers)  # 输出: [0, 2, 4, 6, 8, 10]

print() - 输出内容

将指定的内容打印到控制台,是最常用的调试和输出方法。

示例代码:

# 基本输出
print("Hello, Python!")  # 输出: Hello, Python!

# 输出多个值
name = "Alice"
age = 30
print("Name:", name, "Age:", age)  # 输出: Name: Alice Age: 30

# 格式化输出
print(f"{name} is {age} years old.")  # 输出: Alice is 30 years old.

# 输出到文件
with open('output.txt', 'w') as f:
    print("Save to file", file=f)

内置函数分类速查表

Python 3.11 共有69个内置函数,按功能分类如下:

类别 函数列表 说明
数据类型转换 int(), float(), str(), bool(), list(), tuple(), set(), dict(), bin(), hex(), complex() 在不同数据类型之间进行转换
数学运算 abs(), divmod(), max(), min(), pow(), round(), sum() 执行基本数学计算
迭代与循环 enumerate(), filter(), iter(), map(), next(), range(), reversed(), sorted(), zip() 处理可迭代对象和序列
对象操作 id(), isinstance(), issubclass(), type(), len(), hash() 检查和操作对象属性
输入输出 input(), open(), print() 处理输入输出操作
其他功能 callable(), exec(), eval(), help(), dir(), globals(), locals(), vars() 提供高级功能和内省

内置函数使用最佳实践

优先使用内置函数

内置函数通常比自定义函数更高效,经过优化且无错误。例如,使用sorted()而不是自己实现排序算法。

组合使用函数

内置函数可以组合使用,实现更复杂的功能。例如:

# 获取字符串中最长的单词
text = "Python built-in functions are powerful"
longest_word = max(text.split(), key=len)
print(longest_word)  # 输出: functions

避免过度使用

虽然内置函数强大,但某些情况下自定义函数可读性更好。例如,复杂逻辑使用自定义函数比嵌套多个内置函数更清晰。

Python内置函数教程 © 2023 | 掌握基础,高效编程

本教程仅用于学习目的,Python是Python软件基金会的商标

发表评论