內建函式

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

本章重點

  • 第 1 章:
    • 內建函式、模組與套件

 

  • 第 2 章:
    • 自訂函式

 

  • 第 3 章:
    • 錯誤處理
Intermediate Python for Developers

我們已會用的函式

# Printing
print("Password is accepted!")
Password is accepted!

 

# Checking data types
type(print)
builtin_function_or_method
# Password attempts
for attempt in range(1, 4):
    print("Attempt", attempt)
Attempt 1
Attempt 2
Attempt 3
Intermediate Python for Developers

內建函式

  • 用更少程式碼打造功能

$$

$$

$$

  • 效能監控儀表板 🎯

外送 App

Intermediate Python for Developers

max() 與 min()

# List of preparation times (minutes)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]

# Find the longest preparation time print(max(preparation_times))
48.57
# Find the shortest preparation time
print(min(preparation_times))
12.06
Intermediate Python for Developers

sum() 與 round()

# Calculate the total preparation time
print(sum(preparation_times))
199.21
# Store total time
total_time = sum(preparation_times)

# Round to one decimal place print(round(total_time, 1))
199.2
Intermediate Python for Developers

len()

  • 計算元素數量
# Count the number of orders
print(len(preparation_times))
7
# Calculate average preparation time
print(sum(preparation_times) / len(preparation_times))
28.4585714
Intermediate Python for Developers

len()

  • 計算字元數(含空白)
# Length of a string
print(len("Burger Hub"))
10
Intermediate Python for Developers

sorted()

# Sort a list in ascending order
print(sorted(preparation_times))
[12.06, 15.67, 19.23, 23.45, 34.56, 
45.67, 48.57]
# Sort a string alphabetically
print(sorted("George"))
['G', 'e', 'e', 'g', 'o', 'r']
Intermediate Python for Developers

函式的好處

  • 以更少程式碼完成複雜任務
# Find total preparation time
print(sum(preparation_times))
199.21
Intermediate Python for Developers

函式的好處

# Find total preparation time
# Create a variable to increment
time_count = 0

# Loop through preparation times for time in preparation_times:
# Add each time to time_count time_count += time
print(time_count)
  • sum() 可重複使用,且更短、更乾淨、 也更不易出錯!
19.23
34.9
83.47
106.92
118.98
153.54
199.21
Intermediate Python for Developers

一起來練習吧!

Intermediate Python for Developers

Preparing Video For Download...