English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle des flux Python

Fonction en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Variables globales, locales et non locales en Python

Dans cet article, vous découvrirez les variables globales, locales, non locales en Python et où les utiliser.

Variables globales

Dans Python, les variables déclarées en dehors d'une fonction ou dans un domaine global sont appelées variables globales. Cela signifie qu'elles peuvent être accédées à l'intérieur ou à l'extérieur d'une fonction.

Let's see an example of how to create a global variable in Python.

Example1:Créer une variable globale

x = "global"
def foo():
 print("intérieur x:", x)
foo()
print("extérieur x:", x)

When we run the code, the output will be:

intérieur x: global
extérieur x: global

Dans le code ci-dessus, nous avonsxcréé en tant que variable globale et définissant foo() pour imprimer la variable globalex。Enfin, nous appelons foo() pour imprimerxla valeur.

Si vous souhaitez modifierxla valeur.

x = "global"
def foo():
 x = x * 2
 print(x)
foo()

When we run the code, the output will be:

Si vous souhaitez modifier

Que faire de la valeur ?

Pour réaliser cette fonctionnalité, nous avons utilisé le mot-clé global. Pour plus d'informations, veuillez visiterMots-clés globaux Python

Variables locales

Les variables déclarées à l'intérieur d'une fonction ou dans un domaine local sont appelées variables locales.

Example2:Accès à une variable locale en dehors de sa portée

def foo():
 y = "local"
foo()
print(y)

When we run the code, the output will be:

NameError: le nom 'y' n'est pas défini

La sortie affiche une erreur car nous essayons d'accéder à une variable locale y dans le domaine global, tandis que la variable locale ne fonctionne que dans foo() ou dans un domaine local.

Voyons un exemple de comment créer une variable locale en Python.

Example3:Créer une variable locale

Généralement, nous déclarons une variable à l'intérieur d'une fonction pour créer une variable locale.

def foo():
 y = "local"
 print(y)
foo()

Lorsque nous exécutons le code, il affichera :

local

Voyonsle problème précédent,oùxest une variable globale, que nous voulons modifier à l'intérieur de foo()x

Variables globales et locales

Ici, nous allons montrer comment utiliser à la fois les variables globales et locales dans le même code.

Example4:Utiliser à la fois les variables globales et locales dans le même code

x = "global"
def foo():
 global x
 y = "local"
 x = x * 2
 print(x)
 print(y)
 
foo()

When we run the code, the output will be:

global global 
local

Dans le code ci-dessus, nous déclarons x comme variable globale et y comme variable locale dans la fonction foo(). Ensuite, nous utilisons l'opérateur de multiplication*Modifier la variable globale x et afficher x et y en même temps.

After calling foo(), the value of x becomes global global because we use x * 2Print global twice. Then, we print the value of the local variable y, that is, the local variable.

Example5: Global and local variables with the same name

x = 5
def foo():
 x = 10
 print("local x:", x)
foo()
print("global x:", x)

When we run the code, the output will be:

local x: 10
global x: 5

In the code above, we used the same name x for both global and local variables. When we print the same variable, we get different results because the variable is declared in two scopes, namely the local scope inside foo() and the global scope outside of foo().

When we print a variable inside foo(), it outputs local x: 10. This is called the local scope of the variable.

Similarly, when we print a variable outside of foo(), it will output global x: 5. This is called the global scope of the variable.

Nonlocal variable

Nonlocal variables are used for nested functions that have undefined local scope. This means that the variable cannot be in the local scope nor in the global scope.

Let's see an example of how to create a global variable in Python.

We use the nonlocal keyword to create a nonlocal variable.

Example6: Create a nonlocal variable

def outer():
 x = "local"
 
 def inner():
 nonlocal x
 x = "nonlocal"
 print("inner:", x)
 
 inner()
 print("outer:", x)
outer()

When we run the code, the output will be:

inner: nonlocal
outer: nonlocal

In the code above, there is a nested function inner(). We use the nonlocal keyword to create a nonlocal variable. The inner() function is defined within the scope of another function external().

NoteIf we change the value of a nonlocal variable, these changes will appear in the local variable.