If I write
for i in range(5):
print i
Then it gives 0, 1, 2, 3, 4
Does that mean Python assigned 0, 1, 2, 3, 4 to i at the same time?
However if I wrote:
for i in range(5):
a=i+1
Then I call a, it only gives 5
But if I add ”print a” it gives 1, 2, 3, 4, 5
So my question is what is the difference here?
Is i a string or a list or something else?
Or maybe can anyone help me to sort out:
for l in range(5):
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs[l+1]=vs[l]+fs[l]
fs[l+1]=((rs[l]-re[l])
rs[l+1]=rs[l]+vs[l]
#then this code gives vs,fs,rs
If I run this kind of code, then I will get the answer only when l=5
How can I make them start looping?
i.e l=0 got values for vs[1],fs[1],rs[1],
then l=1 got values for vs[2],rs[2],fs[2]……and so on.
But python gives different arrays of fs,vs,rs, correspond to different value of l
How can I make them one piece?
A “for loop” in most, if not all, programming languages is a mechanism to run a piece of code more than once.
This code:
can be thought of working like this:
So you see, what happens is not that
igets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.I assume that when you say “call a, it gives only 5”, you mean like this:
this will print the last value that a was given. Every time the loop iterates, the statement
a=i+1will overwrite the last valueahad with the new value.Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.
I hope this answered your question.