Python Interview Questions and Answers
Question: What are the rules for local and global variables in Python?Answer:In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.
You'd have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects. |
Most helpful rated by users:
- What is Python?
- How do I share global variables across modules?
- How do you set a global variable in a function in Python?
- Why can\'t I use an assignment in an expression?
- What are the rules for local and global variables in Python?