I have found a simple way to pass variables between functions.
However, I am curious to see if another way is simpler, for example by creating a class. Or, indeed, if my approach to pass variables is problematic.
I was recently struggling to understand how variables can be passed between functions.
There are several StackOverflow questions for newbies on this issue (see here, here, and here). Many answers, however, tend to be too specific to the code snippet provided by the questioner.
I want to understand the general workflow. That is, how variableA can be passed to functionA, manipulated, then passed to functionB, changed again, and then output in functionC, for example.
I think I have a solution:
def main():
output()
def function1():
sentence = ("This is short.") # here is a string variable
value = (10) # here is a number variable
return sentence, value # they are returned
def firstAddition():
sentence, value = function1() # variables recalled by running function1()
add1stSentence = "{}at is longer.".format(sentence[0:2]) # string changed
add1stValue = 2 * value # number changed
return add1stSentence, add1stValue # the changed values are returned
def secondAddition(): # This function changes variables further
add1stSentence, add1stValue = firstAddition()
add2ndSentence = "{} This is even longer.".format(add1stSentence)
add2ndValue = 2 * add1stValue
return add2ndSentence, add2ndValue
def output(): # function recalls all variables and prints
sentence, value = function()
add1stSentence, add1stValue = firstAddition()
add2ndSentence, add2ndValue = secondAddition()
print(sentence)
print(str(value))
print(add1stSentence)
print(str(add1stValue))
print(add2ndSentence)
print(str(add2ndValue))
The output of the above code is the following:
This is short. 10 That is longer. 20 That is longer. This is even longer. 40
The original sentence and value variables were passed between the functions.
My way for passing variables has four steps:
- build functionA that manipulates variables;
- return those variables at the end of functionA;
- at start of functionB, recall each variable, which = functionA;
- functionB manipulates variables and returns them again to be further manipulated, or outputs the variables.
My questions are:
(a) Is my way an accepted practice?
(b) Is there a better or more elegant way to pass variables between functions?