0
s = 0

for s in xrange(0, 100):
    print "s before", s
    if s % 10 == 0:
        s += 10
    print "s after", s

result of loop1

s = 0

while s < 100:
    print "s before", s
    if s % 10 == 0:
        s += 10
    s += 1
    print "s after", s

result of loop2

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?

4
  • These are different loops! Commented Aug 9, 2017 at 8:35
  • 1
    Because for sets s from the iterable, and setting s to something else in the loop doesn't change the iterable. Commented Aug 9, 2017 at 8:35
  • You are essentially asking why s = first_thing then s = second_thing didn't change first_thing. Commented Aug 9, 2017 at 8:36
  • yes, thank you very much.GOT IT Commented Aug 10, 2017 at 5:51

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for ur answer and ur link shared.
Thanks very much and sorry for the late reply. And most importantly, you solved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.