livepython.net
CHAPTER 06Comments
6.3  COMMENT OUT

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:

PYTHONedit me
print("Line 1")
# print("Line 2")
print("Line 3")
OUTPUT
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:

PYTHONedit me
# price = 50
print(price)
OUTPUT
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.

your turnType the output

Type what this prints

print("A") # print("B") print("C")
Read the code line by line, then type the output exactly.
your turnFix the code

Make it print only: Welcome!

It should print: Welcome!

print("Welcome!")
print("testing 1 2 3")
This code does not work yet. Fix it, then press Run.

Hide Your Debug Prints

In chapter 3 you learned to add checkpoint prints to see how far your code gets. When the bug is fixed, those extra lines have to go. Commenting them out is a handy middle step:

PYTHONedit me
price = 40
qty = 3
# print("debug: price is", price)
total = price * qty
# print("debug: total is", total)
print("Total:", total)
OUTPUT
Total: 120

The debug lines are still there, ready to switch on again if a new problem shows up. But the user only sees the real output.

Look inside your variables

Debug prints are most useful when they show values:

PYTHONedit me
width = "5"
height = 3
print("debug:", type(width), type(height))
print(width * height)
OUTPUT
debug: <class 'str'> <class 'int'>
555

The output 555 looks strange. The debug line explains it at once: width is a string! So * repeats it. The fix is width = 5 without quotes. Once fixed, comment out the debug line.

Think of a doctor's scan: you use it to find the problem, and you don't hang it on the wall afterwards.

Label your debug prints

Start each one with debug: (or similar). Then they're easy to spot in the output, and easy to find and remove in the code.

Before you finish

Debug lines, even commented out, are clutter in finished code. When everything works, delete them. You'll see this again in the last lesson of this topic.

Comment out debug prints while you work; delete them when you're done.

your turnPick the right idea

Your debug print shows <class 'str'> for a number you want to multiply. What's wrong?

Think about it, then pick one.
your turnPredict the output

What will this print?

print(2 ** 3 + 1)
Your turn! What will this code show on the screen?

Find a Broken Line by Commenting Out

Sometimes you don't know which line causes a problem. Commenting out lines helps you narrow it down:

  1. Comment out the second half of your code.
  2. Run it. Does the problem disappear?
  3. If yes, the problem is in the half you switched off. If no, it's in the half still running.
  4. Keep halving the suspect part until one line is left.

Think of finding a blown bulb in a long string of lights: test half the string, then half of that half, and so on. A few tests find it, even in a long string.

An example

PYTHONedit me
name = "Sunny"
age = 25
print(f"Name: {name}")
print("Age: " + age)
print("Done")
OUTPUT
Name: Sunny
TypeError: can only concatenate str (not "int") to str

Here the error message already names the line. But imagine the error were less clear. Comment out line 4:

PYTHONedit me
name = "Sunny"
age = 25
print(f"Name: {name}")
# print("Age: " + age)
print("Done")
OUTPUT
Name: Sunny
Done

The error is gone, so line 4 is the problem. Now fix it (an f-string or str(age), from chapter 5) and switch it back on.

When it really helps

This trick shines when there's no error message, just wrong output. Switch off lines one by one, and watch how the output changes. The line that changes it the wrong way is your bug.

Not sure where a bug is? Comment out half the code, and keep halving.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Try a New Version, Then Clean Up

Commenting out also lets you try a new idea while keeping the old one, just in case:

PYTHONedit me
price = 199.5
# print("Price:", price)
print(f"Price: {price:.2f}")
OUTPUT
Price: 199.50

The old way is switched off, and the new one is running. If the new version is worse, swap the # to the other line.

Think of trying on two shirts: you keep the first one on the bed until you've decided.

Clean up before you finish

Commented-out code is fine while you work. In finished code, it causes trouble:

  • Readers wonder: "Is this needed? Should I switch it on?"
  • It goes out of date, like wrong comments.
  • It makes the program longer and harder to read.

So when your program works, tidy it:

  1. Delete commented-out code you don't need.
  2. Delete debug prints.
  3. Keep the real comments that explain why.
  4. Run it once more to check you didn't delete something important.
PYTHONedit me
# Show the price with two decimals, as shops do.
price = 199.5
print(f"Price: {price:.2f}")
OUTPUT
Price: 199.50

Clean, short, and one helpful comment. That's finished code.

Comment out to try things; delete what you don't need before you finish.

your turnOrder the lines

Put the clean-up steps in order

  1. Run it once more to check
  2. Make the program work
  3. Delete debug prints
  4. Delete commented-out code you don't need
These lines are mixed up. Put them back in order, then press Check.

Practice: Comment out

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 48.Fix a Python Program by Commenting Out Debug PrintsEasySolve
  2. 49.Fix a Python Program by Commenting Out an Unfinished LineMediumSolve
  3. 50.Fix and Tidy a Messy Python ProgramHardSolve