I'm new to python.
I don't quite understand how I need to set variables and change them within a function to be used late. My script needs to get an x and y value from a function which are determined by the size of the chart the function creates. These variable need to be passed to a print command later in the script to output html. So let's say I have global variables:
originx_pct = 0.125
originy_pct = 0.11
But these will need to change when the funtion is run...
def makeplot(temp, entropy,preq):
originx_pct = origin.get_points()[0][0]
originy_pct = origin.get_points()[0][1]
Then printed within the javascript of the html page that is written later...
print('var originx_pct = {};'.format(originx_pct))
print('var originy_pct = {};'.format(originy_pct))
The 2 variables don't change and I just don't understand what I need to do to update them and be able to print them (outside the function). I'm assuming that the function does not know about the variables so it can't change them. If I feed the function the 2 variables as arguments, how do i get the values back out for the print part of the script?
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.
In your function, you need to return the values. Change your makeplot
to the following:
def makeplot(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With