I am trying to set the value of a global variable X from inside a function.

I want the value of this variable to change when the function is called. The function will also return the string "pass" when called.

Here is the code:

function[] := (
   X = 10;

However, when I set a new value for X in the function, then call the function


and then call X, I get the OLD value of X, implying that X was never changed.

How would I go about doing this?

  • 1
    $\begingroup$ I can't reproduce the problem. $\endgroup$ – andre314 Feb 29 '20 at 23:45
  • $\begingroup$ I suggest you restart the kernel and try again. $\endgroup$ – andre314 Feb 29 '20 at 23:46
  • 2
    $\begingroup$ You must reevaluate the definition of the function. That said, changing a global from a local context (the function) in this way is just not good practice. $\endgroup$ – ciao Feb 29 '20 at 23:46
  • 1
    $\begingroup$ To analyse the problem you can evaluate ??function and see if there is something abnormal. You can paste screenshot in the question above too. $\endgroup$ – andre314 Feb 29 '20 at 23:50

Evaluate this in a new session with a clean notebook.

x = 42;
function[] := (
  x = 10;

Note that you do not need to use Return. A Wolfram Language function always returns the last expression it evaluates.



You should get the output 42, the current value of x. Now evaluate


You should get the output pass and the output below Dynamic[x] should change to 10. Dynamic is very useful for tracking the changes to global variables when debugging.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.