Sean D
Sean D

Reputation: 117

Can for loops create new variables?

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!

Upvotes: 2

Views: 187

Answers (2)

user1785721
user1785721

Reputation:

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

Upvotes: 1

Rathan Naik
Rathan Naik

Reputation: 1015

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

Upvotes: 1

Related Questions