Every programmer, from a first-time coder to a senior engineer at Google, writes code that doesn't work on the first try. This is completely normal. The difference between a beginner and a pro isn't that pros make fewer mistakes — it's that pros know how to find and fix them quickly. This skill is called debugging.
Where Does the Word "Bug" Come From?
In 1947, a team of computer scientists found an actual moth stuck inside their computer, causing it to malfunction. They taped it into their logbook and wrote "First actual case of bug being found." The term stuck, and we've been calling code problems "bugs" ever since.
Step 1: Read the Error Message
When your code crashes, Python gives you an error message. Don't panic! The error message is actually your best friend — it tells you exactly what went wrong and on which line.
File "game.py", line 5
super_robot.moveForward()
IndentationError: unexpected indent
This message tells us three things: the file name (game.py), the line number (5), and the type of error (IndentationError). That's enough to find and fix the problem.
Step 2: Use Print Statements
Sometimes your code runs but produces the wrong result. When this happens, add print() statements to see what your variables actually contain at different points.
print("Direction is:", direction)
for i in range(3):
super_robot.moveForward()
print("Step:", i)
These prints act like X-ray vision into your program. You can see exactly what's happening at each step and spot where things go wrong.
Step 3: Check the Usual Suspects
Most bugs fall into a few common categories. When you're stuck, check for these first:
- Spelling mistakes: Did you write
moevForwardinstead ofmoveForward? - Indentation errors: Is your code inside the loop actually indented?
- Off-by-one errors: Does
range(5)run 5 times or 4? (It runs 5: 0, 1, 2, 3, 4) - Missing colons: Did you forget the
:after yourfororwhilestatement?
Step 4: Rubber Duck Debugging
This is a real technique used by professional programmers. Grab a rubber duck (or any object) and explain your code to it, line by line, out loud. The act of explaining forces you to slow down and think carefully, and you'll often discover the bug yourself mid-sentence.
Embrace the Bug
Bugs are not failures — they are learning opportunities. Every bug you fix makes you a stronger programmer. So next time your Cyber Dungeon robot walks into a wall, take a deep breath, read the error, and debug like a pro. 🐛