[Tutor] Global Variables

Alan Gauld alan.gauld at btinternet.com
Sat Nov 21 02:31:34 CET 2009


"Joseph Fennell" <josephfennellster at gmail.com> wrote

> I assume that it's because the variable is considered local and the 
> imported
> functions are not technically local to that document.

global in Python means "in the same module" not global across all modules

You are best to pass data into functions as arguments and to pass
it back out as return values.

> cHandler.execute("SELECT * FROM table")
> nl = cHandler.fetchall()
>
> dn = raw_input("User input: ")

> nl2 = []
>
> dname()
> ########
> def dname():
>    global nl

This looks for or creates an nl in your module.
But you don't need the statement because you are not
assigning to nl, merely reading it so Python would find
the global variable if it existed.

>    for ndc in nl:
>        if ndc[1] == dn:
>            nl2.append(ndc,)
>        else:
>            continue

You don't need the else: continue. Python will do that
by default.

You could abbreviate your code usuing a list comprehension:

def dname(nl, dn):
     return [ ndc for ndc in nl if ncd[1] == dn ]

and call it with

nl2 = dname(nl, dn)

> #########
> tuple(nl2) = nl2

I think you are confused here. You could(should?) just do

nl2 = tuple(nl2)

Assuming you want to convert the list in nl2 into a tuple and
store the result in nl2?

If not then I am confused!

> qtysrch()
> #########
> def qtysrch():
>    global nl2
>    for ndc in nl2:
>        if ndc[7] == 0:
>            continue
>        else:
>            print ndc

Again you don't need the global since you are only rading nl2.
And again it would be better practice to pass nl2 into the function
as an argument.

> Any help I can get with this problem would be greatly appreciated.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list