Explain scope and the LEGB rule.

Python control flow and functions · Freshers and experienced

Model answer

Python looks up names in this order: Local (inside the function), Enclosing (outer functions), Global (module) and Built-in. To assign to a global variable inside a function you need the global keyword, and nonlocal for an enclosing function's variable. Avoid global state where you can.

Learn this topic

Functions in Python: def, Arguments and return in the course Python for Beginners: Learn to Code with Real Projects.

Sign in to add your own answer.

More questions