For Python variable (e.g. List and integer) if we do not initialize it, are they always None? Is there any scenario Python will do initialization for us even if we do not initialize it explicitly?
For initialization, I mean,
Foo = []
Goo = 0
thanks in advance, Lin
1 Answer 1
A variable is defined when it is first assigned to a value. Typically, this follows the convention of variable = value. It doesn't become defined until this point, and is defined from this point on until the end of its scope.
If a variable hasn't been defined, attempting to read its data will raise a NameError. On the other hand, [], 0, and None are different types of data values that a defined variable can equal.
Specifically:
[]- An array with no elements0- Theintvalue equal to the number0None- A special data type which is meant to denote that a variable does not have a value. This is very different than a variable not being defined.
Python will not initialize a variable automatically -- how could it? Without knowing what kind of data or values will be operated on, Python can't handle an undefined variable. So it throws an exception, specifically a NameError.
12 Comments
UnboundLocalErrorNone to a variable. It will never automatically assign any value to a variable.
undefinedbut in Python, it would raise a fatal error.