问题
def loop():
d = 0
for x in range(12):
d+=1 #this 'd' is not the same as the one above.
print(d)
In the code above, wouldn't the local variable of the function still be 0? How can I change this to use the function variable instead of the internal variable of the loop?
回答1:
I think you've gotten confused between scope outside of a function and inside of it.
d = 1
def a():
d = 0 # this is a different d from line 1
for x in range(12):
d += 1 # this is the same d as line 3
print(d) # same d as line 3
print(d) # same d as line 1
You probably read about locally scoped variables but have gotten confused. Indenting your line does not create a "new local scope". The only time that happens is within functions.
回答2:
That's not how scope works in Python. The d
in the function is accessible by the loop within the function. They are the same d
.
def loop():
d = 0
for x in range(12):
d+=1 #this 'd' IS the same as the one above.
print(d)
loop()
Running the code proves that it is the same d
.
output:
12
...Your code does what you want. Please run your code and see the output before asking.
回答3:
In a general way Python does not change the scope of variables inside loop (for
, while
) or if
constructs:
you have a single d
variable in your function, regardless of using it inside the loop or not.
There are exceptions, though - one of which is that you can use loops inside list comprehensions or generator expressions - the variables used in these loops are local to the expression - althought, being expressions, they don't allow for general assignment of variables:
def a():
d = 0
any(print(d) for d in range(12))
print("main d:", d)
(This example uses Python 3 print function).
The other exception is the variable to which an exception is assignet in a
try
...except
block. That variable is local to the except block, and ceases existing out of it- but instead of having a nested scope, Python does erase the variable from the current scope:
In [34]: def b():
...: a = 1
...: try:
...: 1 / 0
...: except ZeroDivisionError as a:
...: print(a)
...: print(a)
...:
In [35]: b()
division by zero
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
...
----> 7 print(a)
8
来源:https://stackoverflow.com/questions/41367656/use-local-function-variable-inside-loop