Quoting Python documentation on logical operations ,
In the context of Boolean operations, as well as when expressions are used by flow control operators, the following values ββare interpreted as false: False , None , numeric zero of all types, and empty lines and containers (including lines, tuples, lists, dictionaries, sets, and freezes). All other values ββare interpreted as true.
So, if my_variable fails, if my_variable has any of the above false values, where, since the second will fail, only if my_variable is None . Typically, variables are initialized with None as a placeholder value, and if at some point in time the program is not None , then they will know that some other value is assigned to it.
For instance,
def print_name(name=None): if name is not None: print(name) else: print("Default name")
Here the print_name function expects one argument. If the user provides it, then it may not be None , so we print the actual name passed in by the user, and if we donβt miss anything, None will be assigned by default. Now we check, not < name None , to make sure that we print the actual name instead of Default name .
Note. If you really want to know if your variable is defined or not, you can try this
try: undefined_variable except NameError as e: