Python (Scripting) - undefining variables using None and del
by
Jeremy Canfield |
Updated: November 06 2023
| Python (Scripting) articles
None is often used to undefine a variable. Technically speaking, this does not undefine the variable, as the variable remains defined with a value of None.
#!/usr/bin/python3
foo = "Hello"
bar = "World"
print(f"foo = {foo}")
print(f"bar = {bar}")
foo = None
bar = None
print(f"foo = {foo}")
print(f"bar = {bar}")
In this example, the following should be returned.
foo = Hello
bar = World
foo = None
bar = None
del can be used if you really want to undefine the variable.
#!/usr/bin/python3
foo = "Hello"
print(f"foo = {foo}")
del foo
try:
foo
except NameError:
print("foo is undefined")
else:
print(f"foo = {foo}")
In this example, the following should be returned.
foo = Hello
foo is undefined
Did you find this article helpful?
If so, consider buying me a coffee over at