Dive Into Python Python for experienced programmers |

## 1.10. Defining variables

Now that you think you know everything about dictionaries, tuples, and lists (oh my!), let's get back to our example program, `odbchelper.py`.

Python has local and global variables like most other languages, but it has no explicit variable declarations. Variables spring into existence by being assigned a value, and are automatically destroyed when they go out of scope.

Example 1.25. Defining the `myParams` variable

    if __name__ == "__main__":
        myParams = {"server":"mpilgrim", \
                    "database":"master", \
                    "uid":"sa", \
                    "pwd":"secret" \
                    }

Several points of interest here. First, note the indentation. An `if` statement is a code block and needs to be indented just like a function.

Second, the variable assignment is one command split over several lines, with a backslash (“`\`”) serving as a line continuation marker.

When a command is split among several lines with the line continuation marker (“`\`”), the continued lines can be indented in any manner; Python's normally stringent indentation rules do not apply. If your Python IDE auto-indents the continued line, you should probably accept its default unless you have a burning reason not to.

Strictly speaking, expressions in parentheses, straight brackets, or curly braces (like defining a dictionary) can be split into multiple lines with or without the line continuation character (“`\`”). I like to include the backslash even when it's not required because I think it makes the code easier to read, but that's a matter of style.

Third, you never declared the variable `myParams`, you just assigned a value to it. This is like VBScript without the `option explicit` option. Luckily, unlike VBScript, Python will not allow you to reference a variable that has never been assigned a value; trying to do so will raise an exception.

Example 1.26. Referencing an unbound variable

    >>> x
    Traceback (innermost last):
      File "<interactive input>", line 1, in ?
    NameError: There is no variable named 'x'
    >>> x = 1
    >>> x
    1

You will thank Python for this one day.

Further reading

- Python Reference Manual shows examples of when you can skip the line continuation character and when you have to use it.