Interpreting that the counter value of python for loop cannot be changed in the middle

Asked 2 years ago, Updated 2 years ago, 329 views

It's simple, but for example, to output 0,2,4,6,8... and even numbers, I thought of the following code:

for i in range(10):
    print(i)
    i=i+1

However, the output of this result is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
At the i=i+1 stage, it seems that you can increase i by one, but it seems that it will be restored when repeated.
Please tell me about this interpretation.Does it mean that i in for is only local, so it will be reset during looping?Do you mean you don't really understand the relationship between global and local variables?

Please tell me how to change the value of i in the for loop and take it over to subsequent loops.

python

2022-09-30 21:57

1 Answers

The Python document says the following, which is different from the basic usage in C language.
The i in question is not a loop counter, but a sequential extraction of each element in the integer list created by range(10).
In other languages, it is similar to a feature called foreach.

4.2.for statement

Python's for statement is a little different from the for statement the reader may be familiar with in C or Pascal languages. Unlike constantly repeating arithmetic sequences (like Pascal), or allowing users to define both repeat steps and stop conditions (like C, Python's for statement repeats over any sequence (list or string).The order of iterations is the order in which the elements appear during the sequence.

4.3.range() function

The built-in function range() is useful if you need to iterate over several rows.This function generates an arithmetic sequence:

How to change the value of i in the for loop and take it over to subsequent loops would be to have a separate i variable for repetition.

i=0
For c in range (10):
    print(i)
    i=i+2

A similar method would be to use the while loop instead of the for loop.

i=0
while i<10:
    print(i)
    i=i+2


2022-09-30 21:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.