Commenting Out Code to Test and Debug
Switch a Line Off with #
Put a # in front of a line of code, and Python skips it, just like any comment. This is called commenting out a line:
print("Line 1")
# print("Line 2")
print("Line 3")Line 1 Line 3
Line 2 is still there, but it doesn't run. To switch it back on, remove the #. That's called uncommenting.
Think of a light switch for each line: # turns it off, removing # turns it on again. Nothing is lost.
Why not just delete the line?
- You might want it back in a minute.
- You're testing what happens without it.
- You want to keep an old version for comparison.
Commenting out is quick, safe and easy to undo.
The keyboard shortcut
Most code editors comment out the selected lines with Ctrl + / (Cmd + / on a Mac). Press it again to uncomment. Try it in any live editor on LivePython.
Be careful with variables
If you comment out the line that creates a variable, later lines that use it will fail:
# price = 50
print(price)NameError: name 'price' is not defined
It's the same "create before you use" rule from chapter 4.
Put # in front of a line to switch it off; remove the # to switch it back on.