CommencezCommencez gratuitement

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

Voir le cours

Instructions de l’exercice

  • Assignez à echo_word la chaîne word, concaténée avec elle-même.
  • Utilisez le mot-clé nonlocal pour modifier la valeur de echo_word dans la portée englobante.
  • Modifiez echo_word pour qu'il soit echo_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 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'
____
Modifier et exécuter le code