Why does the order of numbers[i] += result and result +=numbers[i] matter? What does += do? What exactly is iterating? What exactly is looping? n = [3, 5, 7] def total(numbers): result = 0 for i in range(len(numbers)): numbers[i] += result return result VS. n = [3, 5, 7] def total(numbers): result = 0 for i in range(len(numbers)): result += numbers[i] return result
Lets see your questions in order:
numbers[i] += result is the same as
numbers[i] = numbers[i] + result If you switch the places of
result it will go into
result. (Because the original one goes into
2) Look at number 1
3) Iteration is a general term for taking each item of
something, one after another. Any time you use a loop, explicit or
implicit, to go over a group of items, that is iteration.
4) For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the While Loop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -
For loop from 0 to 2, therefore running 3 times.
for x in range(0, 3): print "We're on time %d" % (x)
Hope this helps answer your questions!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.