Better Programming

Advice for programmers.

Follow publication

Member-only story

Find a Bug in Python Code: A Little Thing Does So Much

Marcin Kozak
Better Programming
Published in
6 min readNov 9, 2022

--

A colorful worm (bug) is visible through a magnifying glass. Five small bug-like things can be seen around the colorful bug.
Looking for a bug using a magnifying glass. Source: Image by the author’s wife, Justyna.

In this article, I will show you a tiny little bug in Python. It’s common, as I have made it too often. Maybe a dozen, maybe even twenty times — far more often than I consider acceptable. But since I’ve made it so often, I usually spot it rather easily.

Below, I will explain a strategy you can use to find this and other bugs. While this seems like our little game, this is actually how you could approach debugging.

Your task is to find one or more bugs in the code. How to do it? It’s your call, so choose your method. You can, for instance:

  1. Just read the code and the traceback, and try to find the bug. This is easier for some snippets than for others.
  2. Copy and paste the code to your IDE, text editor, or whatever you work with. Then run the app and try to find the bug using the traceback. You can also use the simplest non-interactive tools that help in debugging, like print(), the logging module, and the like.
  3. Copy and paste the code to your editor/IDE as above, then use the debugger of your choice to find the bug(s). This is interactive debugging.

None of these approaches is better than the others. Each of them teaches different skills, so you should try all of them. Perhaps a good approach is to start with method (1), then, if that doesn’t work, try method (2), and if you still cannot find the bug, try method (3).

That way, you move from the easiest and quickest method to the most advanced one. This partially reflects real-life coding practice, which is how I usually proceed. Honestly, I usually move immediately to the third method when I do not see the bug after the first glance, that is, when using the first method.

Do not underestimate the second method, though. It’s important and teaches something of extraordinary importance: reading and understanding of traceback.

So, let’s jump into the code. Try to find the bug. The good news is that this one is easy to fix. But to fix it, you have to find it. When you succeed in finding it, fixing it is a matter of seconds.

The Code

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Marcin Kozak
Marcin Kozak

Written by Marcin Kozak

A full professor, interdisciplinary researcher, data scientist, statistician, Python, R and Go developer, open-source contributor — and a devoted writer

No responses yet

Write a response