Use local function variable inside loop [closed]

我们两清 提交于 2020-01-14 06:55:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!