How to change for-loop iterator variable in the loop in Python?

后端 未结 5 1515
旧巷少年郎
旧巷少年郎 2021-01-22 05:02

I want to know if is it possible to change the value of the iterator in its for-loop?

For example I want to write a program to calculate prime factor of a number in the

5条回答
  •  执笔经年
    2021-01-22 05:25

    It is not possible the way you are doing it. The for loop variable can be changed inside each loop iteration, like this:

    for a in range (1, 6):
        print a
        a = a + 1
        print a
        print
    

    The resulting output is:

    1
    2
    
    2
    3
    
    3
    4
    
    4
    5
    
    5
    6
    

    It does get modified inside each for loop iteration.

    The reason for the behavior displayed by Python's for loop is that, at the beginning of each iteration, the for loop variable is assinged the next unused value from the specified iterator. Therefore, whatever changes you make to the for loop variable get effectively destroyed at the beginning of each iteration.

    To achieve what I think you may be needing, you should probably use a while loop, providing your own counter variable, your own increment code and any special case modifications for it you may need inside your loop. Example:

    a = 1
    while a <= 5:
        print a
        if a == 3:
            a = a + 1
        a = a + 1
        print a
        print
    

    The resulting output is:

    1
    2
    
    2
    3
    
    3
    5
    
    5
    6
    

提交回复
热议问题