เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

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!"))
แก้ไขและรันโค้ด