Why a variable can be accessible outside the loop in Python? [duplicate]
问题 This question already has answers here : Scoping in Python 'for' loops (6 answers) Closed 4 years ago . Consider this example: for iter in xrange(10): myvar = iter print myvar # 9 Here myvar is clearly outside the loop? But it is still accessible. If this is Perl, it will throw an error. What's the reason behind such feature in Python? Is it harmful? What's the best practice then, to declare a variable before looping? 回答1: There is no new scope created by the for loop (Ruby also behaves the