The Python scope concept is generally presented using a rule known as the LEGB rule:
__Local, Enclosing, Global, and Built-in scopes.__ ** ## local and global scope.
Global :
Trying to update a global variable from within a function:
counter = 0 # A global name
>>> def update_counter():
... counter = counter + 1 # Fail trying to update counter
...
>>> update_counter()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in update_counter
UnboundLocalError: local variable 'counter' referenced before assignment
</code>
>>> counter = 0 # A global name
>>> def update_counter():
... global counter # Declare counter as global
... counter = counter + 1 # Successfully update the counter
...
>>> update_counter()
>>> counter
1
>>> update_counter()
>>> counter
2
>>> update_counter()
>>> counter
3
</code>
>>> global_counter = 0 # A global name
>>> def update_counter(counter):
... return counter + 1 # Rely on a local name
...
>>> global_counter = update_counter(global_counter)
>>> global_counter
1
>>> global_counter = update_counter(global_counter)
>>> global_counter
2
>>> global_counter = update_counter(global_counter)
>>> global_counter
3
</code>
Nonlocal :
The following example shows how you can use nonlocal to modify a variable defined in the enclosing or nonlocal scope:
>>> def func():
... var = 100 # A nonlocal variable
... def nested():
... nonlocal var # Declare var as nonlocal
... var += 100
...
... nested()
... print(var)
...
>>> func()
200
</code>
>>> nonlocal my_var # Try to use nonlocal in the global scope
File "<stdin>", line 1
SyntaxError: nonlocal declaration not allowed at module level
>>> def func():
... nonlocal var # Try to use nonlocal in a local scope
... print(var)
...
File "<stdin>", line 2
SyntaxError: no binding for nonlocal 'var' found
</code>
algorithm analysis.
simulating a dice roll using Python: Here we will be using the random module since we randomize the dice simulator for random outputs.
Function used:
random.randint() : This function generates a random number in the given range. Below is the implementation.