본문 바로가기
Python(Eng. ver)

13. Scope of Variable in Python

by 곽정우 2024. 3. 18.

1. Scope in Python

In Python, the scope of a variable refers to the region of the program where the variable can be referenced and modified. There are four main types of scopes in Python.

 

1-1.  Local

Local scope refers to variables defined within a function. They are only accessible within that function.

 

1-2.  Enclpsing

Enclosing scope refers to the scope of an outer function when referencing a variable from an inner function.

1-3. Global

Global scope refers to variables defined at the top level of a script, which makes them accessible throughout the entire script file.

 

1-4. Built-in

Built-in scope refers to the scope of Python's built-in functions and modules. Examples include print() and len().

 

2. Python Variable Scope

Understanding and managing variable scope is crucial for code readability, maintainability, and preventing unexpected errors.


Local Scope

  • User can have multiple variables with the same name in different functions.
  • Local variables cannot be accessed or modified from outside the function.
  • The nonlocal keyword can be used to reference and modify variables in the enclosing scope.

Enclosing Scope

  • Inner functions can directly reference variables from outer functions.
  • The nonlocal keyword can be used to reference and modify variables in the enclosing scope.

Global Scope

  • Useful when you need to use the same variable in multiple functions.
  • Excessive use can reduce code readability.
  • Consider using modules and packages for efficient variable management.

Built-in Scope

  • Provides access to functions and modules provided by the Python interpreter.
  • Built-in functions cannot be modified or redefined.

'Python(Eng. ver)' 카테고리의 다른 글

15. Object-oriented programming and Class  (0) 2024.03.18
14. Callbacks and Lambdas in Python  (0) 2024.03.18
12. User-Defined Function  (0) 2024.03.15
11. Collections and Loops  (0) 2024.03.15
10. Loop Statement in Python  (0) 2024.03.14