-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy paththe-keyword-nonlocal-and-nested-functions.py
More file actions
40 lines (32 loc) · 1.19 KB
/
the-keyword-nonlocal-and-nested-functions.py
File metadata and controls
40 lines (32 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'''
The keyword nonlocal and nested functions
100xp
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.
Instructions
-Assign to echo_word the string word, concatenated with itself.
-Use the keyword nonlocal to alter the value of echo_word in the enclosing scope.
-Alter echo_word to echo_word concatenated with '!!!'.
-Call the function echo_shout(), passing it a single argument 'hello'.
'''
# Define echo_shout()
def echo_shout(word):
"""Change the value of a nonlocal variable"""
# Concatenate word with itself: echo_word
echo_word = word * 2
#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
nonlocal echo_word
#Change echo_word to echo_word concatenated with '!!!'
echo_word = echo_word + '!!!'
# Call function shout()
shout()
#Print echo_word
print(echo_word)
#Call function echo_shout() with argument 'hello'
echo_shout('hello')