[Tutor] variables question.
Alan Gauld
alan.gauld at btinternet.com
Wed Nov 10 21:49:25 CET 2010
"Jeff Honey" <jeffh at pona.net> wrote
> I have a question about where variables are exposed in python.
Take a look at the namespaces topic in my tutor for more details
but...
> I have a monolothic script with a number of functions defined,
> can those functions share variables?
Yes but its usually bad practice.
Python considers module level variables to be "global".
global vars can be read inside a functon within the same module.
global vars can be changed inside a function in the same module
provided they are declared as global within the function:
foo = 42
def f():
global foo # use the global var
foo = 66
return foo
print foo
print f()
print foo
> can I instantiate them outside the function of where they are
> needed?
Yes, see foo above
> do they need to be wrapped in quotes, ever? For example:
>
> blah = 123
blah refers to an integer
> foo = 'somestring'
foo refers to a string. literal strings need quotes
bar = raw_uinput('?') # bar refers to a strintg input by the user
> def function(foo):
> code that needs foo
> anotherfunction(blah)
No problem
> def anotherfunction(blah):
> code that needs blah
> code that uses foo
This needs a global foo line added at the top.
> def function(blah, foo):
> anotherfunc(blah)
> anotherfunc(foo)
No problem. blah and foo are local variables inside function().
They are passed as arguments to anotherfunc() whioch weill
assign the objects to their parameters and treat as local
variables within anotherfunc()
> ..what about my python being called from some parent script
> (something OTHER than python)
Thats possible but trickier
> that instantiates blah and foo FOR me?
As is this.
But bopth are easier if its another Python script.
> Can I just plug those into my code like I would normally?
No.
> I guess this is more about HOW and WHERE I can
> make variables available for use.
See my tutorial topic...
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list