Skip to content
Advertisement

Referring to variables of a function outside the function

JavaScript

The result is:

NameError: name ‘a’ is not defined

Is it possible to use a outside the function?

Advertisement

Answer

In python the scope is a function, or class body, or module; whenever you have the assignment statement foo = bar, it creates a new variable (name) in the scope where the assignment statement is located (by default).

A variable that is set in an outer scope is readable within an inner scope:

JavaScript

A variable that is set in an inner scope cannot be seen in outer scope. Notice that your code does not even ever set the variable as that line is not ever run.

JavaScript

To make something like you wanted, a variable set within a function, you can try this:

JavaScript
Advertisement