Arbitrary keyword arguments
Arbitrary positional arguments เป็นวิธีหนึ่งในการเพิ่มความยืดหยุ่นให้กับฟังก์ชัน นอกจากนี้ยังสามารถใช้ arbitrary keyword arguments ได้อีกด้วย
ในแบบฝึกหัดนี้ให้นำฟังก์ชัน concat ที่สร้างไว้ในแบบฝึกหัดก่อนหน้ามาปรับแก้เพื่อให้รับ arbitrary keyword arguments ได้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python ระดับกลางสำหรับนักพัฒนา
คำแนะนำการฝึกหัด
- กำหนดฟังก์ชัน
concat()ให้รับ arbitrary keyword arguments โดยตั้งชื่อว่าkwargs - ภายในฟังก์ชัน ให้วนลูปผ่าน ค่า ของ keyword arguments โดยใช้
kwargเป็นตัววนซ้ำ - เรียกใช้
concat()โดยส่ง keyword arguments ได้แก่startเท่ากับ"Python",middleเท่ากับ"is"และendเท่ากับ"great!"
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define a function called concat
def ____(____):
"""Concatenates keyword arguments into a single string with spaces."""
result = ""
# Iterate over the Python kwargs
for ____ in kwargs.____():
result += " " + kwarg
return result
# Call the function
print(____(____="Python", ____="is", ____="great!"))