What are local variables and global variables in Python?
What are local variables and global variables in Python?
In Python, variables can be classified as either local or global based on their scope, that is, the region of the program where they can be accessed and modified.
Local variables are defined within a function and their scope is limited to that function itself. This means they can only be accessed and manipulated within the function in which they are declared. Once the function execution is completed, these local variables are destroyed. For example, if you define a variable x
inside a function func()
, you cannot access x
outside of func()
without causing an error[2][3][4].
Global variables, on the other hand, are defined outside any function, typically at the top level of the Python script. These variables have a global scope, which means they can be accessed and modified from anywhere in the program, whether inside functions or outside. If you declare a variable x
at the top level of your script, it can be accessed within any function or block within that script. To modify a global variable inside a function, you must declare it as global
within the function to avoid Python treating it as a local variable[3][4][6].
Here's a simple example to illustrate the use of local and global variables:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào