I've been running into an issue with Python where I get an `UnboundLocalError` stating that I can't access a local variable called 'diameter' because it isn't assigned a value. I'm trying to understand why Python seems to be unable to recognize that I want to use a global variable. Can someone explain how Python determines the scope of variables and what I need to do to work with global or nonlocal variables in my functions?
2 Answers
Python follows strict rules regarding variable scope. A variable defined in a function is local to that function, so if you want 'diameter' to be accessible from the outer function, use `nonlocal` instead of `global` to explicitly tell Python to reference the outer variable. Also, make sure to check this comprehensive article on scopes for more detail!
It's all about how Python handles variable scope. If you assign a variable inside a function, Python treats it as a local variable unless you specify it with the `global` keyword. So if you want to alter 'diameter' from the outer function, you'll need to declare it as global at the top of your function.

Yeah, I found that article super helpful! It really clarifies the differences in scope between local, global, and nonlocal variables.