In python variables come in two flavors, local and global. Local variables can only be seen from within the function (and they are different each call to the function) while global can be seen from everywhere (and are persistent).
Also it's possible for having a global and local variable with the same name. If you have a local variable in a function it's the local variable that name refers to.
In order to determine if a variable in a function is local or global you would have to check how it's used. Basically it's assumed to be local unless:
- It's declared as being global using the
global statment
- It's not being assigned to.
In your first try you assign to stuff and stuff2 at the beginning of megaf so it's considered local (since you didn't declare it as being global). Consequently you can't access them outside megaf.
In your try to fix this by assigning to stuff and stuff2 outside of megaf you still assign to them in megaf making stuff and stuff2 local to megaf. The uses of stuff and stuff2 refers to the local variable, but as you haven't assigned to the local variable before using them (note that the outside assignment to stuff and stuff2 is to the global variable which is different).
There's two workarounds. First the dirty one is to simply declare them as being global:
def function():
ciao = stuff + stuff2
return ciao
def megaf():
global stuff, stuff2
stuff = 1
stuff2 = 3
for t in range(10):
stuff += 1
stuff2 += 2
print function()
this is dirty as it's often regarded as poor practice to use global variables. The other solution is to pass them as parameters to function as mentioned in the other answers.
stuffandstuff2intofunction.