Debugging With Print
In this tutorial, we'll use print statements to inspect what your program is doing.
Debugging means finding and fixing problems in your code. One of the simplest debugging tools is print().
When a program does something unexpected, print the values you are unsure about.
Inspecting a Variable
price = 10
quantity = 3
total = price * quantity
print("total is", total)
This confirms what total contains.
Checking the Order of Code
Sometimes you want to know which lines run:
print("Step 1")
age = 16
if age >= 18:
print("Step 2: adult branch")
else:
print("Step 3: child branch")
print("Step 4")
The output tells you which branch Python chose.
Printing Before and After
When a variable changes, print it before and after:
score = 10
print("Before:", score)
score = score + 5
print("After:", score)
This helps you see exactly where the change happened.
Make Debug Prints Obvious
Use labels:
print("DEBUG age:", age)
Without labels, output becomes confusing:
print(age)
print(score)
print(total)
Three numbers on the screen are not very helpful unless you know what they mean.
Clean Up Afterwards
Debug prints are temporary. Once you have solved the problem, remove them or turn them into useful output for the user.
Practice
Write a program that calculates a final score from two smaller scores. Add debug prints before and after the calculation.