"for" loops are throwing me for a loop. In the example: for numChickens in range(0, numHeads+1), I am having difficulty wrapping my head around the numChickens variable. Where is it declared or initialized? What, exactly, are we iterating here (i.e. for...what, exactly)?
In general a loop will assign (or bind as they like to say in this course) an initial value to a 'loop variable' (which would be numChickens) then increment that variable (by 1 as a default) until the highest value in the range is reached. Thus, in examining the code you have quoted, numChickens appears to be assigned to 0, incremented by one, until it reaches numHeads (or that plus one) Whether numChickens ever is used with the value numHeads + 1 depends on the 'boundary case' which I am sure we can cover if need be... CLK
Fydor's explanation is correct in languages like C, C++ and to some extent Java. However, in python for loops work very differently. In python the for loop has the form: for variable in container: block of statements working with variable This code is semantically equivalent to i = 0 while i < len(container): variable = container[i] block of statements working with variable i += 1 If you look at the range function, you'll see that all it does is return a list of numbers from 0 to the number you've passed as your argument. So range(5) returns [0,1,2,3,4], and range(numHeads+1) would return [0, 1, 2, ..., numHeads-1, numHeads] Though it will use the actual numbers, not the symbolic values I've described here.
Polpaks explanation offers some details of how Python assigns value to the loop variable. I suppose it is a matter of opinion to say that Python loops are 'very different' from other language loops. The following two loops produce the same output: in c: int numChickens; int numHeads = 5; for(numChickens = 0; numChickens < numHeads + 1; ++numChickens) printf("%d \n", numChickens); in Python numHeads = 5 for numChickens in range(0, numHeads + 1) : print(numchickens) Both loop forms can be generalized, and it is true that at least conceptually there is the idea in Python of iterating through a container (defined by the range operation) while in c the concept is more of defining the n+1st term of a sequence in terms of the n'th term.
Join our real-time social learning platform and learn together with your friends!