Legb Rule in Python
A so LEGB rule, which would be named just after Python scope for names, is used by Python to resolve names. Here's a brief explanation of what each of these phrases means:
The LEGB rule controls the manner wherein Python looks up names as a type of name lookup operation.
In conclusion, names are resolved when we utilize nested functions by first verifying the local scope or the local scope of the innermost function. Then, from the deepest scope to the outermost scope, Python examines all surrounding scopes of outer functions. Python then checks the global as well as built-in scopes if there isn't a match. We will receive a warning if the name cannot be located.
Depending on where we are within the code during execution, there will only ever be a maximum of four active Python scopes: local, enclosing, global, the built-in. The global as well as built-in scopes, in contrast hand, will always be at least two of the active scopes. These two scopes are constantly at our disposal.
The value of x is 8
In the global namespace, variable x will be defined with the value 2, and function f will be defined with one parameter that prints out a string and the parameter's value. When f is called, the local namespace of the function initializes the parameter a with the value 8. On line 4, Python starts by looking for a in the local namespace. It then moves on to the innermost namespace and finds a term a that maps to an integer with the value 8. Python then stops looking there and8outputs "The value of a is," followed by the value of the a that it discovered, "8."
The value of a is 2
Line 1 defines the global namespace variable a, which has the value 2. In the global namespace, we define the function f on line 3. We call f on line 8. This generates a function g and a parameter y with the value 3 in a local namespace (inside the global namespace). Line 6 calls g, which creates a new local namespace with the parameter c having the value 3. The local namespace that was previously created by invoking f is now an enclosing namespace.
We have now arrived at the print statement! Python now looks for an object with the name an in the namespaces already in use. Python tries an enclosing namespace because there isn't a similar variable in the local namespace. Python looks in the global namespace because a is not declared there either. We discover a name a that corresponds to an object with the value 2 there. Python thus outputs "The value of a is," then "2," which is the value of a in the global namespace.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week