'using xrange output not expected
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?
Solution 1:[1]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
