This article is part of in the series

Regardless of how someone approaches learning to write Python, the process of fixing bugs doesn’t become intuitive until they have spent a long time learning to code.  Many Python novices tend to feel stuck and frustrated when the code they write doesn’t work, and they cannot figure out what went wrong. We shortlisted ten tips about bug fixing to help you improve your approach to troubleshooting code.  These tips will teach you the fundamentals that you will be able to use throughout your coding career.

How to Solve Python Bugs for Python Novices

Here are ten beginner tips about solving Python bugs for Python novices.

#1 Build on Code That Already Works

Even the best programmers sometimes doubt whether their approach to writing a Python program is the right way to go about it. So, when in doubt, it is a good idea to look at someone else’s code that already works. Coding has a steep learning curve; initially, it’s better to rely on an existing structure and tweak it as needed.  If you’re learning to write Python from a book or an online course, you will have access to many reference programs.  However, if you’re working independently on a project, you must try Googling a script that accomplishes what you want to do. Run the code and verify it works correctly before making any changes to it. Always make small changes and test it at every step to see if your code has introduced any bugs.

#2 Use the Print Function Frequently

To understand code, you should know the value of the variables as every line is executed. If unsure, using the print function is an excellent way to get a sense of the variable values. Run the program, and look at the console to see how the values change. You might find that variables are getting set to null or another unexpected value. It is best practice to print a fixed string before printing a variable. This way, your print statements don’t run together, and you can tell what variable is being printed where. In some programs, you might have trouble figuring out whether a block of code is running at all. A simple print statement like “running” or “got here” is enough to determine if there is a mistake in the program’s control flow. Check if statements and for loops for inconsistencies. 

#3 Comment-Out Code

Python, like the majority of programming languages, allows you to comment. Comments are a method for developers to make notes in the code. However, the text inside the comments is ignored by Python when it tries to execute the code.  You can use this feature to temporarily prevent some code from getting detected by the language runtime without deleting it from the file. This is called “commenting out” code. Doing this is as simple as putting the comment character “#” at the beginning of the lines of code you don’t want the runtime to detect. If you are working with a long script, you can comment out the blocks of code that don’t have anything to do with the changes you’re implementing. This way, the program may run faster and allow you to search the remainder of the program for mistakes. It’s important to use this feature carefully since it’s easy to comment out code that sets the variables that are being used later in the program. All the text in a comment is skipped entirely, so the statements later in the program will not have access to the variables set in a line that has been commented out. Further, you must also remember to remove the comment characters after you’re done testing the rest of the code.

#4 Run the Code Whenever You Make a Change

Whether you’re starting with a blank file or not, changing the code non-stop for an hour and only then running it is not a good strategy.  The odds are that you will be confused with several small errors that are now stacked on each other – most of which could have been prevented if only you had taken it slow. The worst thing about this situation is that it could take longer to peel back the layers of what you’ve done and figure out where you’re going wrong. The longer you spend coding and not testing, the larger the volume of code where mistakes could have been made.  Since it’s impossible to code and test a program at every update and stay productive, running the script every few minutes is best. The best programmers remember that every time they run their code, they receive feedback about their work. They are able to determine whether they’re taking the project in the right direction or it’s starting to fail.

#5 Take a Break and Walk Away

Python novices and new programmers in general tend to easily get caught up in the details of the implementation at hand. Getting bogged down in the details and losing sight of the bigger picture is a common experience many programmers learn to deal with. If you notice that you haven’t made much progress in 20 or 30 minutes, it’s best to step away from the code for some time. Picking up another activity and completely forgetting about the code for a few minutes will give you the rest you need to figure it out when you get back at it. Getting a glass of water or a cup of coffee, taking a short walk, or having a snack is a nice way to reset your mind and pull back. You can explore other approaches when after the break. This tip often seems unsatisfying to people that haven’t tried it because most people think, “if I walk away now, I’ll forget the details.” Starting over again and leaving the code in a broken state both feel like a step back rather than a step forward. But using this tip can be surprisingly helpful, with a plethora of studies indicating benefits such as improvement in performance, lower stress, and improved creativity.

#6 Read the Error Message

It’s easy to feel like giving up when code you have put a lot of work into throws an error. New Python programmers also feel lost when they see stack traces. But it’s important to remember that most error messages are accurate and descriptive.  Reading the error message lets you figure out whether something was missing or there was a typo in the code. You may also have missed a line, leaving the program unable to do what it needs to do. Error messages indicate what went wrong, but if you cannot understand the error, at the very least, you will know what line the problem is in. You can use that information to start looking for bugs.

#7 Search for the Error Online

One of the best ways to learn what an error message means is to copy and paste it into Google. You can search the last line of a stack trace on Google.  You can expect to find a few stackoverflow.com pages with others in the community asking questions about the error along with answers and explanations. While this approach often works, it can be hit-or-miss depending on whether the error is specific or generic. Always read the code in the question and compare it with your own. This is the only way to understand whether the answer is relevant to your problem.  Next, read some comments and a few answers to see if the solutions work for you.

#8 Guess and Check

In the early stages of your programming career, you will often find many potential solutions and not be 100% sure about how you will fix a bug.  In such circumstances, you must try two or three different solutions and see what happens. As indicated in tip #4, run your code often so you get feedback quickly and can change your approach if it doesn’t seem to be working. The odds are that when you try to fix the code, you may introduce some other error into the program. This can make it difficult to understand whether you’re getting closer to a fixed program or have taken a step back. To avoid breaking the code completely and starting over, try not to go too far down a rabbit hole of a solution you found online or otherwise. It’s important to keep yourself open to trying out a few solutions before you decide to ask someone else for help. One of the first things any programmer will ask you when you approach them for help is to list a few solutions you tried. Having tried a few solutions and explaining them to whoever you’re asking for help will not only give them a clue as to what to try next but also show your commitment to fixing the problem.

#9 If You Cannot Pinpoint the Problem, Run a Binary Search

The larger the program you run, the higher the number of places you need to check for an error. When a project exceeds 50 lines, figuring out where the errors are in the code can be challenging. While the stack trace and the error message can give you a clue about where to look for bugs, sometimes, these aren’t helpful at all. If you find yourself in this situation, it’s best to run a binary search. It will allow you to zone in on the section of your program that is not acting as expected. Here’s a brief breakdown of how a binary search works: At a high level, a binary search involves splitting data in half and searching both halves for whatever you’re looking for. Once the search figures out which half the data is in, that half of the data is split into two, and both are searched to find where the object of interest (in this case, an error) is. A binary search is one of the fastest ways to find an error in the code since it breaks the program into halves and allows you to hone in on where the issue is. When looking for bugs in a program, run just the first half of it by commenting out the second half. Print the results of the halfway-run program. If the results look as expected, you can conclude that the first half of the program is running fine. The problem you’re looking for may be in the second half of the program. However, if there is a problem in the results, the error is in the first half of the program. Repeat the process of running parts of the code over and over until you pinpoint the source of the issue. This tip combines many of the tips mentioned earlier in this post.

#10 Ask for Help

If you’ve tried everything but can’t figure out what is going wrong in the program, you may be ready to ask someone for help. Regardless of whether you’re asking a friend, an instructor, or a colleague for help with your bug, ensure you have all the following components to ask an excellent question:

  1. Explain the goal.
  2. Show the code with the error.
  3. Show the stack trace and the error message.
  4. Explain what you’ve tried and why those solutions did not work.

Sometimes, when you write these details down or go through them in your mind, a new solution might come to mind. The thinking behind why this happens is that asking a good question makes the solution obvious. For this reason, many programmers gather all the facts listed above before going to someone for help. This tip might just solve your problem.