Global and Local Variables in Python

In Python, variables can either be global or local. It is essential to understand the difference between the two types of variables because it can affect how your code works.

A global variable is a variable that can be accessed anywhere in the code, regardless of where it was declared. On the other hand, a local variable is a variable that can only be accessed within the function where it was declared.

Let's look at an example:

x = 5 def my_function(): print(x) my_function()

In this example, x is a global variable because it was declared outside of the function. When my_function() is called, it prints the value of x, which is 5.

However, if we declare x inside the function, it becomes a local variable:

def my_function(): x = 5 print(x) my_function()

In this example, x is a local variable because it was declared inside the function. When my_function() is called, it prints the value of the local variable x, which is also 5.

It is important to note that local variables take precedence over global variables. This means that if you have a local variable with the same name as a global variable, the local variable will be used instead.

x = 5 def my_function(): x = 10 print(x) my_function() print(x)

In this example, my_function() declares a local variable x with a value of 10. When my_function() is called, it prints the value of the local variable x, which is 10. However, when the global variable x is printed after calling my_function(), it still has a value of 5.

In conclusion, understanding the difference between global and local variables in Python is essential for writing effective code. Global variables can be accessed anywhere in the code, while local variables can only be accessed within the function where they were declared. Local variables take precedence over global variables with the same name.

グローバル変数とローカル変数[JA]