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

คีย์เวิร์ด 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'
____
แก้ไขและรันโค้ด