Variable Scope and Nested Functions
In Python, where a variable is defined determines where it can be accessed — this is called scope.
Functions can also be nested, meaning one function can exist inside another.
Let’s explore both.
1. Local vs Global Scope
Variables defined inside a function are local
— they only exist while the function runs.
Variables defined outside any function are global
and can be used throughout the script.
message = "Hello from global scope" def show_message(): message = "Hello from local scope" print(message) show_message() print(message)
Explanation:
- Inside the function, a new
message
variable is created. - The global variable is unaffected.
2. Using global
Keyword
To modify a global variable inside a function, use the global
keyword.
counter = 0 def increase(): global counter counter += 1 increase() print("Counter:", counter)
Explanation:
- Without
global
, Python treatscounter
as a new local variable. - With
global
, it updates the variable outside the function.
3. Nested Functions
A function can be defined inside another function. The inner function is local to the outer one.
def outer(): print("Outer function") def inner(): print("Inner function") inner() outer()
Explanation:
inner()
can only be called insideouter()
.- Useful for organizing logic and encapsulating behavior.
Summary
Concept | Description |
---|---|
Local Scope | Variables inside a function |
Global Scope | Variables outside all functions |
global keyword | Allows modifying global variables inside functions |
Nested Functions | Functions defined inside other functions |
What’s Next?
Next, you’ll learn how to handle errors gracefully using try
, except
, and related tools.
학습 자료
AI 튜터
디자인
업로드
수업 노트
즐겨찾기
도움말
코드 에디터
코드 실행
코드 생성
실행 결과