the resource i am using to learn python has you perform modules within its own website. i think it was originally designed for students of this particular university so that is why i have tagged this with homework, even though it is not.
anyway:
they had me perform this task:
Define a function prod(L) which returns the product of the elements in a list L.
i got this function to work using this code:
def prod(L):
i = 0
answer = 1
x = len(L)
while i < x:
answer = answer * L[i]
i = i + 1
if i == x:
return answer
the very next module talks very briefly about For-In loops. and they pose the question:
Define the function prod(L) as before, but this time using the new kind of loop.
i have tried looking through other resources to understand how exactly to use this but i am not following anything. can anybody explain, preferably in plain english, how a for-in loop works?
for reference: here is EVERYTHING that they talked about regarding the for-in loop
Looping through lists It is very common (like in the previous
exercise) to loop through every value in a list. Python allows a
shortcut to perform this type of an operation, usually called a “for
all” loop or a “for each” loop. Specifically, when L is a list, this
code
for x in L: «loop body block»does the following: first x is set to
the first value in L and the body is executed; then x is set to the
second value in L and the body is executed; this is continued for all
items in L.
i just cant fully wrap my head around this. im not looking for answers as i am doing this for knowledge growth – but i feel like im falling behind on this ):
In the explanation given,
Lis an iterable. This can be a sequence (e.g. list, tuple, string) or a generator (e.g.xrange()). Each element of the iterable is bound to the namexin turn, and the loop body is executed.