In Python, the global keyword modifies variables at the program level, while the nonlocal keyword modifies variables in an enclosing function scope; by default, Python creates local variables inside functions, so using global or nonlocal is necessary when you need to modify variables from outside the current function scope.
深度探索
先修知识
- 暂无数据。
后续步骤
- 暂无数据。
深度探索
Title:Python global vs nonlocal Explained in 60 Seconds 🔥 | Python Scope Explained #hitcodear本站添加:
Python has a scope trap that confuses even senior developers. Global versus non-local.
By default, Python creates a new local variable inside functions. So, if you try modifying an outside variable directly, you'll get unexpected behavior or errors. That's where global and non-local come in. Global is used to modify variables from the global program scope. In this example, x starts as 10.
Inside the change function, we use global x, then update it to 20.
Next comes the interesting part. Inside the bank function, we create a nested function called deposit. Here, balance is a global variable. So, we use global balance to update it. But transactions belongs to the outer bank function. So, inside deposit, we use non-local transactions to modify that enclosing variable. Then every deposit updates both the balance and the transaction count. Finally, when we call account with 5200, the balance increases and transactions keep tracking correctly. That's the real difference. Global modifies program level variables while non-local modifies variables from an enclosing function scope.
相关推荐
Re: 🗣️📍theprophedu📍2026 GST 103 CLASS (E-EXAM REVISION)
theprophedu
636 views•2026-06-04
WEB TECHNOLOGIES UNIT-2 | Degree 4th sem BCOM Computers web technologies unit-2 full explanation💯✅
LearnwithSahera
1K views•2026-05-29
More tests are always better? How to use AI to identify tests that bring little value
Alliance4Qualification
335 views•2026-05-29
Search Algorithms Explained in 60 Seconds! 🤖💨
samarthtuliofficial
218 views•2026-06-01
People of Game of Thrones using JavaScript DOM
AltCampus
296 views•2026-05-30
Instagram accounts got PWNed
EricParker
13K views•2026-06-03
Introduction to Problem Solving Part - 1 | Lecture 1 | Intermediate DSA
ascensionix
107 views•2026-05-29
So What's Odin Lang Even Good For
TechOverTea
131 views•2026-06-01











