🐍 Python常用内置函数完全指南:从print到zip的实用手册

引言

Python内置函数是Python解释器随时可用的函数,无需导入任何模块。掌握这些函数能让你写出更简洁、更Pythonic的代码。本文将详细介绍最常用的内置函数及其实用技巧。

一、输入输出函数

1. print() - 打印输出

# 基本用法
print("Hello, World!")

# 多参数输出
name = "Alice"
age = 25
print("Name:", name, "Age:", age)

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

# 自定义分隔符和结束符
print("A", "B", "C", sep="-", end="\n\n")

2. input() - 用户输入

# 获取字符串输入
name = input("Enter your name: ")

# 获取数字输入
age = int(input("Enter your age: "))

二、类型转换函数

# int() - 转换为整数
print(int("42"))      # 42
print(int(3.14))      # 3

# float() - 转换为浮点数
print(float("3.14"))  # 3.14

# str() - 转换为字符串
print(str(42))        # "42"

# bool() - 转换为布尔值
print(bool(1))        # True
print(bool(0))        # False
print(bool(""))       # False

三、数学函数

# abs() - 绝对值
print(abs(-5))        # 5

# round() - 四舍五入
print(round(3.14159, 2))  # 3.14

# divmod() - 商和余数
print(divmod(17, 5))  # (3, 2)

# pow() - 幂运算
print(pow(2, 3))      # 8

四、序列操作函数

# len() - 获取长度
print(len("Hello"))   # 5
print(len([1, 2, 3])) # 3

# range() - 生成数字序列
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# enumerate() - 带索引遍历
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits):
    print(f"{idx}: {fruit}")

# zip() - 并行遍历
names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

五、高阶函数

# map() - 映射
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16]

# filter() - 过滤
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)    # [2, 4]

# 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]

六、其他实用函数

# isinstance() - 类型检查
print(isinstance(42, int))       # True
print(isinstance([1, 2], list))  # True

# hasattr() / getattr() - 属性操作
class Person:
    name = "Alice"

print(hasattr(Person, 'name'))   # True
print(getattr(Person, 'name'))   # Alice

# open() - 文件操作
with open('file.txt', 'r') as f:
    content = f.read()

总结

Python内置函数是提升编码效率的利器。从基本的print()、input()到强大的map()、filter()、zip(),熟练掌握这些函数能让你的代码更加简洁优雅。建议在日常编程中多加练习,形成肌肉记忆。

关键要点:

  • 类型转换函数:int(), float(), str(), bool()
  • 序列操作:len(), range(), enumerate(), zip()
  • 函数式编程:map(), filter(), sorted()
  • 实用工具:isinstance(), hasattr(), open()
posted @ 2026-03-23 02:34  码小小小仙  阅读(2)  评论(0)    收藏  举报