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

ฟังก์ชันที่มี default argument หลายตัว

ตอนนี้คุณได้กำหนดฟังก์ชันที่ใช้ default argument แล้ว แต่อย่าหยุดแค่นั้น! ขั้นต่อไปจะได้ลองกำหนดฟังก์ชันที่มี default argument มากกว่าหนึ่งตัว และเรียกใช้ฟังก์ชันนั้นในหลายรูปแบบ

หลังจากกำหนดฟังก์ชันแล้ว จะเรียกใช้โดยระบุค่าให้กับ default argument ทุกตัว จากนั้นจะลองเรียกใช้อีกครั้งโดยไม่ส่งค่าให้กับ default argument ตัวใดตัวหนึ่ง เพื่อดูว่าผลลัพธ์ของฟังก์ชันเปลี่ยนแปลงไปอย่างไร

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Python เบื้องต้น: การเขียนฟังก์ชัน

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เติม header ของฟังก์ชันโดยใช้ชื่อฟังก์ชันว่า shout_echo โดยรับอาร์กิวเมนต์ word1, default argument echo ที่มีค่าเริ่มต้นเป็น 1 และ default argument intense ที่มีค่าเริ่มต้นเป็น False ตามลำดับนี้
  • ในส่วน body ของคำสั่ง if ให้แปลงออบเจกต์ string echo_word เป็นตัวพิมพ์ใหญ่ทั้งหมด โดยใช้เมธอด .upper()
  • เรียก shout_echo() โดยส่ง string "Hey", ค่า 5 สำหรับ echo และค่า True สำหรับ intense แล้วกำหนดผลลัพธ์ให้กับตัวแปร with_big_echo
  • เรียก shout_echo() โดยส่ง string "Hey" และค่า True สำหรับ intense แล้วกำหนดผลลัพธ์ให้กับตัวแปร big_no_echo

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Define shout_echo
def ____(____, ____, ____):
    """Concatenate echo copies of word1 and three
    exclamation marks at the end of the string."""

    # Concatenate echo copies of word1 using *: echo_word
    echo_word = word1 * echo

    # Make echo_word uppercase if intense is True
    if intense is True:
        # Make uppercase and concatenate '!!!': echo_word_new
        echo_word_new = ____ + '!!!'
    else:
        # Concatenate '!!!' to echo_word: echo_word_new
        echo_word_new = echo_word + '!!!'

    # Return echo_word_new
    return echo_word_new

# Call shout_echo() with "Hey", echo=5 and intense=True: with_big_echo
with_big_echo = ____

# Call shout_echo() with "Hey" and intense=True: big_no_echo
big_no_echo = ____

# Print values
print(with_big_echo)
print(big_no_echo)
แก้ไขและรันโค้ด