0
def test_scope():    
    i = 0
    while(i<3):
        j = i
        i += 1
    
    print (j)

I saw other's code like this. j only exists in the while scope, but it seems valid in Python. In PyCharm, it gives a warning that 'j' can be undefined, but it doesn't throw an error. I likes to define the 'j' with some initial value before the while loop.

Is this good practice in Python using an out-of-scope variable?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • Python doesn't have block scoped variables. – Barmar Feb 08 '22 at 06:35
  • Is everything top-level code (bad idea anyway), or inside a function? Note that if the first four lines are inside one function, and the `j` is elsewhere, you won't be modifying the same `j`. – Frank Yellin Feb 08 '22 at 06:35
  • 1
    If the loop never runs, `j` will never be assigned. That's what Pycharm is warning you about. This has nothing to do with scope.\ – Barmar Feb 08 '22 at 06:37
  • @FrankYellin It's inside a function, but I am not used to let j be accessible outside of a loop. – marlon Feb 08 '22 at 06:44
  • 1
    Then you need to broaden your horizon. It's quite common to set variables inside a loop and use them after. How else will you get information from the loop? – Barmar Feb 08 '22 at 06:50
  • In that case, I'm perfectly happy with this code. I have no problem with loops setting variables outside the loop. This is a common practice. – Frank Yellin Feb 08 '22 at 07:00
  • @FrankYellin, but it's annoying that PyCharm highlights it as yellow text: "local reference might be referenced before assignment. " Why not initialize the 'j' to some sensible value before the while loop, as other languages do? – marlon Feb 08 '22 at 17:58

0 Answers0