Changing Global Variables Within A Function In Python
Solution 1:
You need to use the global
keyword in your function.
originx_pct = 0.125
originy_pct = 0.11defmakeplot(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.
Solution 2:
In your function, you need to return the values. Change your makeplot
to the following:
defmakeplot(temp, entropy, preq):
local_originx_pct = origin.get_points()[0][0]
local_originy_pct = origin.get_points()[0][1] # the local_ in the names doesn't mean anything, it is just for clarity.return local_originx_pct, local_originy_pct
Then, when you call the function, set your variables to its return value.
originx_pct, originy_pct = makeplot(args_and_stuff)
This is considered better practice then directly changing global variables as in ltd9938's answer. It helps to prevent accidentally messing stuff up for other functions. More reasons not to use global
Solution 3:
You can either declare the global variables in the function with the lines global originx_pct
and global originy_pct
, or you can return them when you run the function. To do that, you can do
defmakeplot(temp, entropy,preq):
return (origin.get_points()[0][0],origin.get_points()[0][1])
Or
defmakeplot(temp, entropy,preq):
return origin.get_points()[0][0:2]
If origin.get_points()[0]
has only two elements, you do just this:
defmakeplot(temp, entropy,preq):
return origin.get_points()[0]
Then, in your main function, put
originx_pct, originy_pct = makeplot(temp, entropy,preq)
Although I'm not clear on why you're passing temp
, entropy
, and preq
to makeplot
, since you don't seem to be using them.
Post a Comment for "Changing Global Variables Within A Function In Python"