Scoping in Python 'for' loops

前端 未结 6 1201
名媛妹妹
名媛妹妹 2020-11-22 03:52

I\'m not asking about Python\'s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were m

6条回答
  •  死守一世寂寞
    2020-11-22 04:26

    For starters, if variables were local to loops, those loops would be useless for most real-world programming.

    In the current situation:

    # Sum the values 0..9
    total = 0
    for foo in xrange(10):
        total = total + foo
    print total
    

    yields 45. Now, consider how assignment works in Python. If loop variables were strictly local:

    # Sum the values 0..9?
    total = 0
    for foo in xrange(10):
        # Create a new integer object with value "total + foo" and bind it to a new
        # loop-local variable named "total".
        total = total + foo
    print total
    

    yields 0, because total inside the loop after the assignment is not the same variable as total outside the loop. This would not be optimal or expected behavior.

提交回复
热议问题