2

I came across this problem online and used it on visualizer to see how this works. It looks to me that a new variable called guess was created using the for loop.

Question: Did the for loop create a new variable called "guess"? If not, how was the value of guess utilized outside the loop in the if/else statement?

cube = 8

for guess in range(cube+1):
    if guess**3 >= abs(cube):
        break
if guess**3 != abs(cube):
    print(cube, "is not a perfect cube")
else:
    if cube < 0:
        guess = -guess
    print("The cube root of", str(cube), "is", str(guess))

I'd highly appreciate some feedback on this. Thank you!

Sean D
  • 107
  • 1
  • 2
  • 7
  • 2
    outside the loop, `guess` is the last value calculated before the loop ends (or breaks) – PRMoureu Sep 01 '17 at 04:50
  • 2
    https://stackoverflow.com/questions/10563613/does-python-officially-support-reusing-a-loop-variable-after-the-loop and https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – TessellatingHeckler Sep 01 '17 at 04:52

2 Answers2

1

From the doc:

Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop.

So yes, the for loop create a new variable.

The only case in which guess will not be created is in case that the sequence by which the for loop iterate is empty, e.g.

>>> for abcde in []: pass
... 
>>> abcde
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abcde' is not defined

as the opposite of:

>>> for abcde in [1]: pass
... 
>>> abcde
1
1

Python formally acknowledges that the names defined as for loop targets (a more formally rigorous name for "index variables") leak into the enclosing function scope.

The official word The Python reference documentation explicitly documents this behavior in the section on for loops

The for-loop makes assignments to the variables(s) in the target list. [...] Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop.

Read More Here

Rathan Naik
  • 758
  • 7
  • 19