[Tutor] scope of a global dictionary?

Marilyn Davis marilyn at deliberate.com
Fri Feb 6 15:45:40 EST 2004


Making materials for this class exposes my ignorance to myself.
Like they say, you never know a subject until you teach it.

More ignorance exposed:

My understanding is that a global variable can be accessed, but not
altered in a function's code block, unless the global declaration is
used:

x = 3
def f():
    print x       <-  is ok
def g():
    x += 1        <-  not ok
def h():
    global x
    x *= 2        <-  ok again

But I wrote this little dictionary example and it doesn't need the
global declaration to add new entries to the dictionary.

I can't explain this.  Can anyone help me?

#! /usr/bin/python2.2
''' A dictionary application, using a dictionary.'''

dict = {'yield':'return, but start here with next next() call',
        'pass':'do nothing'}

def add_some():
    while 1:
        word = raw_input('Word: ')
        if word == '':
            return
        meaning = raw_input('Meaning: ')
        dict[word.lower()] = meaning

if __name__ == '__main__':
    add_some()
    words = dict.keys()
    words.sort()
    for word in words:
        print word, ':', dict[word]
        
##################################################
#  OUTPUT:
#  bash-2.05a$ ./scoped.py
#  Word: break
#  Meaning: jump out of loop and don't do an else
#  Word: 
#  break : jump out of loop and don't do an else
#  pass : do nothing
#  yield : return, but start here with next next() call
#  bash-2.05a$ 


Thank you some more!

Marilyn




More information about the Tutor mailing list