Q. What is scope? What is the scope resolving rule of Python?

Answer:-

Parts of program within which a name is legal and accessible, is called scope of the name.
• The scope resolving rule of Python is LEGB rule. 

LEGB Rule : The acronym stands for Local, Enclosing, Global, and Built-in, which represent the four levels of variable lookup.


Local (L): The local scope refers to the current function or code block. When a variable is referenced within a function or code block, the interpreter first checks the local scope to see if the variable is defined there. If found, it uses that value.

Enclosing (E): The enclosing scope refers to the scope of the function or code block that contains the current function or code block. If the variable is not found in the local scope, the interpreter checks the enclosing scope to see if the variable is defined there. This process continues until the variable is found or the global scope is reached.

Global (G): The global scope refers to the module-level scope. If the variable is not found in the local or enclosing scopes, the interpreter looks for it in the global scope. Variables defined outside any functions or code blocks are in the global scope.

Built-in (B): The built-in scope refers to the pre-defined names and functions available in Python. If the variable is not found in any of the previous scopes, the interpreter checks the built-in scope. This includes built-in functions like print() or len().


The LEGB rule defines the order in which these scopes are searched when a variable is referenced. It helps in understanding how Python resolves variable names and allows you to have variables with the same name in different scopes without conflicts.

4 Comments

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

  1. Please elaborate your type A answers

    ReplyDelete
    Replies
    1. Our mission is for short answer, so that you can learn easily .

      Delete
  2. Can u please define LEGB rule?

    ReplyDelete

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post