Home > Blockchain >  How to avoid variable after statement `for` in python?
How to avoid variable after statement `for` in python?

Time:12-29

When I write programs with python, something offen happens like:

for i in range(5):
    print("before",i)
    for j in range(5):
        for i in range(5):
            pass
    print("after",i)

which output:

before 0
after 4
before 1
after 4
before 2
after 4
before 3
after 4
before 4
after 4

I often use variables with the same name in the outer loop and multiple inner loops, which will cause bugs but are hard to find. What is the best practice to avoid this situation?

What I mean is that when I focus on writing business code, it is difficult for me to detect or often ignore the problem of duplicate variable names, which wastes a lot of debugging time. In fact, I have been writing code in a C-like style. I'm trying to find a way to stop getting this type of error

CodePudding user response:

Use different names! There's no way to re-use a variable name in any scope.

CodePudding user response:

Use a linter, e.g. pylint. The purpose of a linter is to help you catch things that are syntactically valid but are considered bad practice, bad style, or likely to be mistakes.

>pylint test.py
************* Module test
test.py:4:8: W0621: Redefining name 'i' from outer scope (line 1) (redefined-outer-name)

CodePudding user response:

Use enter image description here

CodePudding user response:

To be honest, you should not do that. As you have said it makes things way more complicated than it ought to be :D

You could just name them like this:

for i in range(5):
    print("before",i)
    for i2 in range(5):
        for i3 in range(5):
            pass
    print("after",i)

If you are using them in the same block of code, they should be at least not named the same.

But thats just my opinion about it.

CodePudding user response:

Minimize number of nested loops, too. That is an indirect indication that code is suboptimal, at least from readability point of view.

  • Related