The book you refer to is clearly trying to greatly simplify the meaning of None
. Python variables don't have an initial, empty state – Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test
NameError: global name 'x' is not defined
but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None
:
>>> def test(x=None):
... if x is None:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
The fact that this value is the special None
value is not terribly important in this case. I could've used any default value:
>>> def test(x=-1):
... if x == -1:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
…but having None
around gives us two benefits:
-1
whose meaning is unclear, and-1
as a normal input.>>> test(-1)
no x here
oops!
So the book is a little misleading mostly in its use of the word reset – assigning None
to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reset a value to its original, undefined state you must use the del
keyword:
>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined