Le mot-clé nonlocal et les fonctions imbriquées
Poursuivons votre maîtrise de la portée des variables ! 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 la portée englobante.
Cette activité fait partie du cours
Introduction aux fonctions en Python
Instructions de l’exercice
- Assignez à
echo_wordla chaîneword, concaténée avec elle-même. - Utilisez le mot-clé
nonlocalpour modifier la valeur deecho_worddans la portée englobante. - Modifiez
echo_wordpour qu'il soitecho_wordconcaténé avec '!!!'. - Appelez la fonction
echo_shout(), en lui passant un seul argument 'hello'.
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
# 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'
____