Make Your Python Program Bug-Free: 8 Essential Tips

Yang Zhou
TechToFreedom
Published in
6 min readAug 30, 2021

--

Although bugs are nearly inevitable in programming, senior developers can avoid lots of unnecessary bugs and write robust programs.

Why?

On the one hand, they made enough mistakes before thus they can avoid them in similar scenarios.

On the other hand, they are familiar with the programming language they are using, so they know where are the bug-prone points and how to deal with them.

This article will talk about 8 essential points to avoid bugs in Python programs based on my 8-year experience. Hope it’s useful.

0. Mind the Scope of Variables

The scope of Python variables is important but not intuitive for beginners. Bugs may be introduced if we don’t totally understand it.

Let’s see a simple example:

score = 100
def test():
score =0
print(score)

test()
# 0
print(score)
# 100

As shown above, the statement score=0 inside the test() function will not change the global variable’s value. Because Python treats the inside score as a local variable and the outside score as a global variable.

If we really want to change the global variable inside the function, add a statement with the global keyword:

--

--