Due to popular demand, we're back answering more questions from users who are having trouble with scripting their projects!
Question: Why am I unable to assign to a global variable within a function in Python without explicitly declaring it as global? Additionally, how does Python handle access to global variables within functions?
Answer: You should refer to the documentation for clarification: Assigning a value to a global variable without using the 'global' keyword is not allowed. However, variables within a function can access global variables without explicitly declaring them as global.
In simpler terms, you can read the value of a global variable from within a function, but you can't change it without declaring it as global. Without this declaration, any assignments within the function create new local variables with the same name as the global one. These local variables disappear when the function finishes running.
This design choice by Python's creators is likely intentional. While accessing global variables is generally okay, directly modifying them within a function is usually not recommended. So, by requiring the 'global' declaration for modifying global variables, Python encourages better coding practices.