ฟังก์ชันที่มี default argument หลายตัว
ตอนนี้คุณได้กำหนดฟังก์ชันที่ใช้ default argument แล้ว แต่อย่าหยุดแค่นั้น! ขั้นต่อไปจะได้ลองกำหนดฟังก์ชันที่มี default argument มากกว่าหนึ่งตัว และเรียกใช้ฟังก์ชันนั้นในหลายรูปแบบ
หลังจากกำหนดฟังก์ชันแล้ว จะเรียกใช้โดยระบุค่าให้กับ default argument ทุกตัว จากนั้นจะลองเรียกใช้อีกครั้งโดยไม่ส่งค่าให้กับ default argument ตัวใดตัวหนึ่ง เพื่อดูว่าผลลัพธ์ของฟังก์ชันเปลี่ยนแปลงไปอย่างไร
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้น: การเขียนฟังก์ชัน
คำแนะนำการฝึกหัด
- เติม header ของฟังก์ชันโดยใช้ชื่อฟังก์ชันว่า
shout_echoโดยรับอาร์กิวเมนต์word1, default argumentechoที่มีค่าเริ่มต้นเป็น1และ default argumentintenseที่มีค่าเริ่มต้นเป็นFalseตามลำดับนี้ - ในส่วน body ของคำสั่ง
ifให้แปลงออบเจกต์ stringecho_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)