0

Here is the code:

def rand():
  import random
  num = (random.randint(1000,9999))
  print(num)

rand()
print(num)

Within the subroutine, the variable "num" is printed successfully. However, outside of it, when printing is attempted, the following error message is displayed:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(num)
NameError: name 'num' is not defined

Why does this happen, and what are the ways I can work around it?

Revivan
  • 1
  • 4
  • 1
    “Why does this happen” — In a nutshell: because that’s the intention. Function scope is intentionally locally limited, otherwise you couldn’t implement effective encapsulation. – Konrad Rudolph Apr 04 '20 at 16:25
  • @KonradRudolph So, when the variable is stored within a subroutine, it is then deleted when that subroutine ends? – Revivan Apr 04 '20 at 16:29
  • Not directly. Instead, each method call creates a whole new environment (= scope) for the function call execution. Local variables live inside that environment. When the function exits, that whole environment is removed. On a more technical level, these environments are known as “stack frames”, and each function call adds a new stack frame to the [call stack](https://en.wikipedia.org/wiki/Call_stack). – Konrad Rudolph Apr 04 '20 at 16:44
  • 1
    [9.2. Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) ... [4.2. Naming and binding](https://docs.python.org/3/reference/executionmodel.html#naming-and-binding) - I periodically read and re-read those a number of times *in-the-beginning* till it started to sink in. – wwii Apr 04 '20 at 16:55
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) - there are others searching with variants of `python variable scope site:stackoverflow.com` – wwii Apr 04 '20 at 16:57
  • In Python `rand` is a function and not typically referred to as a subroutine. If you want to use that outside of the function, return it and assign that return value to a name in the module's scope. – wwii Apr 04 '20 at 16:59

0 Answers0