Reputation: 114
s = 0
for s in xrange(0, 100):
print "s before", s
if s % 10 == 0:
s += 10
print "s after", s
s = 0
while s < 100:
print "s before", s
if s % 10 == 0:
s += 10
s += 1
print "s after", s
As pictures shown above, why those 2 loops doing similar things, one using xrange while another using while-loop are giving me exact different output?
Upvotes: 0
Views: 65
Reputation: 14689
s
in the first loop is overwritten by the values coming from xrange(0, 100)
whereas in the second loop you are manually initializing the variable s=0
and then incrementing it with s += 10
. So, it's exactly the expected behavior.
You need to have a look into variable scopes in python. Check this discussion: Short description of the scoping rules?
Upvotes: 2