R
14

Why does every beginner tutorial skip explaining variables scope?

I'm 3 weeks into learning Python and every guide shows you how to declare a variable but never says where it actually lives in memory. Just spent 2 hours debugging a function because I didn't know local vs global was a thing. Anybody else run into this wall?
2 comments

Log in to join the discussion

Log In
2 Comments
blair_lewis85
Burned a whole Saturday once because I thought a variable I set at the top of my script would just magically work inside a function. Spoiler alert it didnt. Python just stared at me like I was the idiot. Turns out my variable was living its best life globally while my function was crying over an undefined name. Three weeks in and youre already hitting this wall man just wait til you find out about closure scopes.
3
faithf77
faithf774d ago
Honestly, you're not wrong about the whole global vs local thing being a trap, but @blair_lewis85 I gotta gently push back on that "closure scopes" warning for a three week beginner. Closure scope is more of a JavaScript gotcha with nested functions, not really a Python thing you'd hit early on unless you're doing some weird decorator stuff. In Python, you'd probably run into the "nonlocal" keyword first if you're nesting functions, but that's usually further down the road. Tbh, the real wall after global scoping is usually list comprehensions and how they handle variables differently than loops.
3