In my program, I have several variables within functions that I need to call on in other functions. To do this I made the variables I need global (example:)
def Vcmi1(Vcm, VcmU, Vi1, Vi1U, Pi1, Pi1U, Pi2, Pi2U, m1, m1U, m2, m2U):
global Vcmi1
global Vcmi1U
Vcmi1 = Vi1-Vcm
Vcmi1U = (Vi1U+(((Pi1U+Pi2U)/(Pi1+Pi2))+((m1U+m2U)/(m1+m2))))*Vcmi1
return Vcmi1, Vcmi1U
However, when I use them in a later function, these variables are tuples instead of floats and they cannot be multiplied with other floats (example:)
def initial_momentum_cm_1(m1, m1U, Vcmi1, Vcmi1U, Vcm, VcmU, Vf2, Vf2U, Pi1, Pi1U, Pi2, Pi2U, m2, m2U):
Pcmi1 = Vcmi1*m1
Pcmi1U = (((Vi1U+(((Pi1U+Pi2U)/(Pi1+Pi2))+((m1U+m2U)/(m1+m2)))))+(m1U/m1))*Pcmi1
return Pcmi1, Pcmi1U
I'm relatively new to python so I'm not 100% sure how the global command works (found out about it last night for this purpose). How can I make that tuple into a float and still be able to use it outside of its function?
When you do return v1, u1
, it returns two values. So if you call this function like so
result = Vcmi1(...)
the two values get packed into a tuple and result = (v1, u1)
. An alternative to this is to have them unpacked directly like this
Vcmi1, Vcmi1U = Vcmi1(...)
And then you can pass them onto the next function in the next line. In summary, if your execution happens in main
, it should look something like this (I've renamed your first function so that its easier to understand)
def main():
for caseNumber in xrange(4):
Vcm = raw_input("Enter vcm for case#{}:".format(caseNumber))
#Calculate the two velocities and store them in 2 variables
Vcmi1, Vcmi1U = calculate_velocities(Vcm, VcmU, Vi1, Vi1U, Pi1, Pi1U, Pi2, Pi2U, m1, m1U, m2, m2U)
#Now simply pass these two variables onto the next function
p1, p2 = initial_momentum_cm_1(m1, m1U, Vcmi1, Vcmi1U, Vcm, VcmU, Vf2, Vf2U, Pi1, Pi1U, Pi2, Pi2U, m2, m2U)
The global
is not needed in this case. The namespaces for the variables are valid until the end of main
(or whichever your calling function is)
The only reason you want to use global is if you don't want to pass so many arguments.