The keyword nonlocal and nested functions
Let's once again work further on your mastery of scope! In this exercise, you will use the keyword nonlocal within a nested function to alter the value of a variable defined in the enclosing scope.
Bu egzersiz
Introduction to Functions in Python
kursunun bir parçasıdırEgzersiz talimatları
- Assign to
echo_wordthe stringword, concatenated with itself. - Use the keyword
nonlocalto alter the value ofecho_wordin the enclosing scope. - Alter
echo_wordtoecho_wordconcatenated with '!!!'. - Call the function
echo_shout(), passing it a single argument 'hello'.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
# 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'
____