Topic: access object outside of function?

I was wondering if it was possible to access and modify an object/value from outside of a 'def' function, or have an object value within a function accessible to the whole script.

Example of that I want to do:

#Tells if light is currently on or off:
light_on = True

def lightswitch():
    if light_on:
        print "A simple light switch, in the 'on position'"
    else:
        print "A simple light switch, in the 'off position'"
    
    input = raw_input("> ")

    #Turning light on and off:
    if input == "turn on light" and light_on:
        print "The light is already on."
        lightswitch()
    if input == "turn on light" and not light_on:
        print "The light is now on."
        light_on = True
        forward()
    if input == "turn off light" and light_on:
        print "The room is dark now."
        light_on = False
        forward()
    if input == "turn off light" and not light_on:
        print "The light is already off."
        lightswitch()
    if input == "return":
        forward()
    else:
        print "Invalid command. (hint: 'turn on/off light')"
        lightswitch()

because then I would like to use this modified 'light_on' value in a different function.

Thanks!

Last edited by ponynicker53 (January 25, 2012 22:59)

Thumbs up

Re: access object outside of function?

>>> a = True
>>> def f():
...   global a
...   a = not a
... 
>>> a
True
>>> f()
>>> a
False
>>> f()
>>> a
True
>>>

global variables complicate programs

>>> a = True
>>> def f(a):
...   a = not a
...   return a
... 
>>> a
True
>>> f(a)
False
>>> a = f(a)
>>> a
False
>>> f(a)
True
>>> a = f(a)
>>> a
True
>>> 

global variables -> local variables

Thumbs up