[Solved] Python - basic functions

Hi,

using python, how can I do the following :


def default():
     var=5
     var1=10
     var2=15

def main():
    default()
    print (var)
    print (var2)
    print (var3)

This simplified script returns the following :

UnboundLocalError: local variable ‘var’ referenced before assignment

I don’t want this :


def main():
    var=5
    var1=10
    var2=15
    print (var)

How can I do?

Well use global varibles:
import GameLogic as g
def default():
g.var=5
g.var1=10
g.var2=15
def main():
default()
print g.var
print g.var2
print g.var3
main()

OR use function return:
def default():
var=5
return var
def main():
print default()
main()
/will return ‘5’/

Multiple value returns can be done like this:

def default():
 value1 = 5
 value2 = 10
 value3 = 15
 
 return value1, value2, value3
 
def main():
 val1, val2, val3 = default()
 print val1, val2, val3
 
main()

I think you were getting the error because variables defined in a funtion are local to that function.

I didn’t know that variables defined in a function were local.
Global variables and multiple returns are the solutions I was looking for.
haidme, FunkyWyrm, thank you.

Just for information, are there other ways to do it?