Le mot-clé nonlocal et les fonctions imbriquées
Développons votre maîtrise de la portée ! Dans cet exercice, vous utiliserez le mot-clé nonlocal
à l’intérieur d’une fonction imbriquée pour modifier la valeur d’une variable définie dans sa portée locale.
Cet exercice fait partie du cours
Introduction aux fonctions en Python
Instructions
- Affectez à
echo_word
la chaîne de caractèresword
, concaténée avec elle-même. - Utilisez le mot-clé
nonlocal
pour modifier la valeur deecho_word
dans la portée qui l’entoure. - Modifier
echo_word
enecho_word
concaténé avec « !!! ». - Appelez la fonction
echo_shout()
en lui passant un seul argument, « hello ».
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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'
____