内置函数

Python 中级:面向开发者

Jasmin Ludolf

Senior Data Science Content Developer

本章内容

  • 第 1 章:
    • 内置函数、模块与包

 

  • 第 2 章:
    • 自定义函数

 

  • 第 3 章:
    • 错误处理
Python 中级:面向开发者

已知的函数

# 打印
print("Password is accepted!")
Password is accepted!

 

# 检查数据类型
type(print)
builtin_function_or_method
# 密码尝试
for attempt in range(1, 4):
    print("Attempt", attempt)
Attempt 1
Attempt 2
Attempt 3
Python 中级:面向开发者

内置函数

  • 用更少代码构建功能

$$

$$

$$

  • 性能监控仪表板 🎯

外卖应用

Python 中级:面向开发者

max() 与 min()

# 准备时间列表(分钟)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]

# 查找最长的准备时间 print(max(preparation_times))
48.57
# 查找最短的准备时间
print(min(preparation_times))
12.06
Python 中级:面向开发者

sum() 与 round()

# 计算总准备时间
print(sum(preparation_times))
199.21
# 存储总时间
total_time = sum(preparation_times)

# 四舍五入到1位小数 print(round(total_time, 1))
199.2
Python 中级:面向开发者

len()

  • 统计元素个数
# 统计订单数量
print(len(preparation_times))
7
# 计算平均准备时间
print(sum(preparation_times) / len(preparation_times))
28.4585714
Python 中级:面向开发者

len()

  • 统计字符数(含空格)
# 字符串长度
print(len("Burger Hub"))
10
Python 中级:面向开发者

sorted()

# 按升序排序列表
print(sorted(preparation_times))
[12.06, 15.67, 19.23, 23.45, 34.56, 
45.67, 48.57]
# 将字符串按字母顺序排序
print(sorted("George"))
['G', 'e', 'e', 'g', 'o', 'r']
Python 中级:面向开发者

函数的优势

  • 用更少代码完成复杂任务
# 计算总准备时间
print(sum(preparation_times))
199.21
Python 中级:面向开发者

函数的优势

# 计算总准备时间
# 创建一个累加变量
time_count = 0

# 遍历准备时间 for time in preparation_times:
# 将每个时间加到 time_count time_count += time
print(time_count)
  • sum() 可复用、更短、更清晰,且更不易出错!
19.23
34.9
83.47
106.92
118.98
153.54
199.21
Python 中级:面向开发者

Vamos praticar!

Python 中级:面向开发者

Preparing Video For Download...