ฟังก์ชันในตัว

Python ระดับกลางสำหรับนักพัฒนา

Jasmin Ludolf

Senior Data Science Content Developer

สิ่งที่จะได้เรียนรู้

  • บทที่ 1:
    • ฟังก์ชันในตัว โมดูล และแพ็กเกจ

 

  • บทที่ 2 :
    • ฟังก์ชันที่กำหนดเอง

 

  • บทที่ 3:
    • การจัดการข้อผิดพลาด
Python ระดับกลางสำหรับนักพัฒนา

ฟังก์ชันที่รู้จักกันอยู่แล้ว

# 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
Python ระดับกลางสำหรับนักพัฒนา

ฟังก์ชันในตัว

  • ช่วยสร้างฟีเจอร์โดยใช้โค้ดน้อยลง

$$

$$

$$

  • แดชบอร์ดติดตามประสิทธิภาพ 🎯

แอปส่งอาหาร

Python ระดับกลางสำหรับนักพัฒนา

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
Python ระดับกลางสำหรับนักพัฒนา

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
Python ระดับกลางสำหรับนักพัฒนา

len()

  • นับจำนวนสมาชิกในลิสต์
# Count the number of orders
print(len(preparation_times))
7
# Calculate average preparation time
print(sum(preparation_times) / len(preparation_times))
28.4585714
Python ระดับกลางสำหรับนักพัฒนา

len()

  • นับจำนวนตัวอักษร รวมถึงช่องว่าง
# Length of a string
print(len("Burger Hub"))
10
Python ระดับกลางสำหรับนักพัฒนา

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']
Python ระดับกลางสำหรับนักพัฒนา

ประโยชน์ของฟังก์ชัน

  • ทำงานที่ซับซ้อนได้โดยใช้โค้ดน้อยลง
# Find total preparation time
print(sum(preparation_times))
199.21
Python ระดับกลางสำหรับนักพัฒนา

ประโยชน์ของฟังก์ชัน

# 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
Python ระดับกลางสำหรับนักพัฒนา

มาฝึกกันเถอะ!

Python ระดับกลางสำหรับนักพัฒนา

Preparing Video For Download...