คีย์เวิร์ด nonlocal และฟังก์ชันซ้อนกัน
มาฝึกเรื่อง scope กันต่อ! ในแบบฝึกหัดนี้ จะได้ใช้คีย์เวิร์ด nonlocal ภายในฟังก์ชันซ้อนกัน เพื่อเปลี่ยนค่าของตัวแปรที่กำหนดไว้ใน enclosing scope
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้น: การเขียนฟังก์ชัน
คำแนะนำการฝึกหัด
- กำหนดให้
echo_wordเป็นสตริงwordที่เชื่อมกับตัวเอง - ใช้คีย์เวิร์ด
nonlocalเพื่อเปลี่ยนค่าของecho_wordใน enclosing scope - เปลี่ยนค่า
echo_wordให้เป็นecho_wordที่เชื่อมกับ '!!!' - เรียกใช้ฟังก์ชัน
echo_shout()โดยส่งอาร์กิวเมนต์ 'hello' เพียงตัวเดียว
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define echo_shout()
def echo_shout(word):
"""Change the value of a nonlocal variable"""
# Concatenate word with itself: echo_word
____
# Print echo_word
print(echo_word)
# Define inner function shout()
def shout():
"""Alter a variable in the enclosing scope"""
# Use echo_word in nonlocal scope
____
# Change echo_word to echo_word concatenated with '!!!'
echo_word = ____
# Call function shout()
shout()
# Print echo_word
print(echo_word)
# Call function echo_shout() with argument 'hello'
____