how can i check if a variable is set?

Gerhard Häring gh_pythonlist at gmx.de
Tue Feb 5 15:14:12 EST 2002


Le 05/02/02 à 19:50, maximilianscherr écrivit:
> how cna i check if a variable is set?
> like:
> 
> if variable a doesn't exist then set it to 0
> if it exists do nothing...

You were already told how to do this, but ...

... that's not exactly the best style ;-)

Chances are what you really want is a dictionary, which maps keys to
values, suppose you want to do something like count the number of
occurences of various words:

text = "this text contains text"
words = {}
for word in text.split():
    if not words.has_key(word):
        # First occurence
        words[word] = 1
    else:
        # We found another occurence of this word
        words[word] = words[word] + 1


This can be optimized with the get() method of the dictionary object.
The first parameter of the get() method is the key, the second is a
default value that is used if there is no entry under the given key.

text = "this text contains text"
words = {}
for word in text.split():
    words[word] = words.get(word, 0) + 1

no-everything-that's-possible-is-a-good-solution-ly yours,

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 10.3 °C      Wind: 2.0 m/s




More information about the Python-list mailing list