#1
  1. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2001
    Location
    London, England
    Posts
    14
    Rep Power
    0

    Testing the existnace of variable


    Hi,

    I have a script in which I'd like to test whether or not a particular variable has been defined or not.

    The php equivalent would be something like this:

    if !$MyVariable
    {$MyVariable = "Hello World";}

    else
    {echo $MyVariable;}

    What is the equivalent syntax in Python? Can't seem to find anything in any of the documentation I have.

    Thanks, NICK
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2002
    Location
    California
    Posts
    0
    Rep Power
    0

    Testing the existence of a variable


    Hello,
    You need to assign variables in Python before you can use them. This is
    good programming practice. You can re-define variables later eg:

    #!/usr/bin/env python
    def main():
    testVar=None
    if (not testVar):
    testVar = "Hello World"
    print testVar
    testVar = 3
    print testVar
    if __name__ == "__main__":
    main()

    prints:
    Hello World
    3

    But, I strongly advise you to try to avoid doing this. It makes code difficult to understand and maintain. I suggest you initialise your variables before use.

    Hope that helps,
    Adil
  4. #3
  5. No Profile Picture
    Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2001
    Location
    London, England
    Posts
    14
    Rep Power
    0

    Thanks


    Thanks for that

    NICK
  6. #4
  7. No Profile Picture
    Code Poet
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2002
    Location
    Boston
    Posts
    9
    Rep Power
    0
    To answer your question directly...

    One way to test the existence of a variable would be:

    Code:
    try:
        MyVariable
    except NameError:
        MyVariable = "Hello World"
    print MyVariable
    Best,
    parker

IMN logo majestic logo threadwatch logo seochat tools logo