How to Change a Global Variable from Within a Function

How do I change the value of a global variable inside of a function

Just reference the variable inside the function; no magic, just use it's name. If it's been created globally, then you'll be updating the global variable.

You can override this behaviour by declaring it locally using var, but if you don't use var, then a variable name used in a function will be global if that variable has been declared globally.

That's why it's considered best practice to always declare your variables explicitly with var. Because if you forget it, you can start messing with globals by accident. It's an easy mistake to make. But in your case, this turn around and becomes an easy answer to your question.

changing global variables within a function in python

You need to use the global keyword in your function.

originx_pct = 0.125
originy_pct = 0.11

def makeplot(temp, entropy,preq):
global originx_pct, originy_pct
originx_pct = origin.get_points()[0][0]
originy_pct = origin.get_points()[0][1]

You can read more about global here.

Best way to change value of global value inside a function in Python?

Since you go to the trouble of naming x when you call foo(x), its not too much of a stretch to do x = foo(x):

x = 5

def foo(_):
_ = 10
return _

x = foo(x)

print(x)

Using Global Variables inside a Nested Function in Python

In add, x is not a global variable; it's local to add. You either need to make it global as well, so that add and change are referring to the same variable

def add(): 
global x
x = 15

def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

or you need to declare x in change as nonlocal, rather than global.

def add(): 
x = 15

def change():
nonlocal x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

How to modify a global variable inside a function in javascript, i.e. modify variable in-place

The map function does not modify the original array. Additionally, you seem to be using it incorrectly.

You are using map to set the values of array2 and then setting nums to a copy of array2. This will not modify the original object contained in nums.

Of course, if you log nums within the function, it will give you the updated value, but this value is scoped within the function and won't be accessible outside.

Instead of array methods, for this type of impure programming, you should use a for loop.

var rotate = function(nums, k) {
array2 = Array.from(nums);
for (const i in nums) nums[i] = array2[(i+k)%nums.length];
};


Related Topics



Leave a reply



Submit