下面我将详细讲解16个Python中最常见的基础函数,包括它们的用途、参数、返回值以及示例代码。
CSDN大礼包:《2025年最新全套学习资料包》免费分享
用途:将指定对象输出到标准输出设备(通常是屏幕)
# 基本用法
print("Hello, World!") # 输出: Hello, World!
# 多个参数
print("Name:", "Alice", "Age:", 25) # 输出: Name: Alice Age: 25
# 指定分隔符
print("2023", "12", "31", sep="-") # 输出: 2023-12-31
# 指定结束符
print("Hello", end=" ")
print("World") # 输出: Hello World
用途:返回对象的长度(元素个数)
# 字符串长度
print(len("Python")) # 输出: 6
# 列表元素个数
print(len([1, 2, 3, 4])) # 输出: 4
# 字典键值对数量
print(len({"a": 1, "b": 2})) # 输出: 2
用途:返回对象的类型
print(type(10)) # 输出:
print(type(3.14)) # 输出:
print(type("Hello")) # 输出:
print(type([1, 2, 3])) # 输出:
print(type({"a": 1})) # 输出:
用途:从标准输入读取字符串
name = input("请输入您的名字: ")
print(f"欢迎, {name}!")
# 输入数字时需要转换类型
age = int(input("请输入您的年龄: "))
print(f"明年您将 {age + 1} 岁")
用途:生成一个不可变的数字序列
# 生成0到4的序列
for i in range(5):
print(i, end=" ") # 输出: 0 1 2 3 4
# 生成2到6(不含6)的序列
for i in range(2, 6):
print(i, end=" ") # 输出: 2 3 4 5
# 生成1到10,步长为2的序列
for i in range(1, 10, 2):
print(i, end=" ") # 输出: 1 3 5 7 9
用途:在循环中同时获取索引和值
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
# 输出:
# 索引 0: apple
# 索引 1: banana
# 索引 2: cherry
用途:将多个可迭代对象打包成元组
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
用途:对可迭代对象进行排序
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers)) # 输出: [1, 1, 2, 3, 4, 5, 9]
print(sorted(numbers, reverse=True)) # 输出: [9, 5, 4, 3, 2, 1, 1]
# 对字符串排序
print(sorted("Python")) # 输出: ['P', 'h', 'n', 'o', 't', 'y']
用途:计算可迭代对象中所有元素的总和
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # 输出: 15
print(sum(numbers, 10)) # 输出: 25 (初始值为10)
用途:返回可迭代对象中的最大值或最小值
numbers = [3, 1, 4, 1, 5, 9, 2]
print(max(numbers)) # 输出: 9
print(min(numbers)) # 输出: 1
# 多个参数
print(max(3, 1, 4)) # 输出: 4
用途:对浮点数进行四舍五入
print(round(3.14159, 2)) # 输出: 3.14
print(round(3.14159, 3)) # 输出: 3.142
print(round(3.14159)) # 输出: 3
用途:检查对象是否是特定类的实例
print(isinstance(10, int)) # 输出: True
print(isinstance(10.5, float)) # 输出: True
print(isinstance("Hello", str)) # 输出: True
print(isinstance([1, 2], list)) # 输出: True
用途:返回对象的有效属性列表
print(dir([])) # 列出列表的所有方法
print(dir("")) # 列出字符串的所有方法
print(dir(__builtins__)) # 列出所有内置函数和异常
用途:查看对象或函数的帮助信息
help(print) # 查看print函数的帮助
help(str) # 查看字符串类型的帮助
help(len) # 查看len函数的帮助
用途:执行字符串形式的Python表达式并返回结果
print(eval("3 + 4")) # 输出: 7
print(eval("'Hello' * 2")) # 输出: HelloHello
x = 10
print(eval("x * 2")) # 输出: 20
⚠️ 注意:eval()有安全风险,不要用它来执行不受信任的输入。
用途:执行字符串形式的Python代码
exec("print('Hello from exec!')") # 输出: Hello from exec!
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
"""
exec(code) # 输出: Hello, Alice!
同样,exec()也有安全风险,应谨慎使用。
这些基础函数构成了Python编程的基石。掌握它们的使用方法对于编写高效、简洁的Python代码至关重要。在实际编程中,这些函数经常被组合使用,以解决各种复杂的问题。
记住,理解函数的参数和返回值是正确使用它们的关键。同时,查阅官方文档(使用help()函数)是深入学习每个函数的好方法。