Bootstrap FreeKB - Python (Scripting) - undefining variables using None and del
Python (Scripting) - undefining variables using None and del

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 3bf241 in the box below so that we can be sure you are a human.