Issue
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 below way :
def primeFactors(number):
for i in range(2,number+1):
if (number%i==0)
print(i,end=',')
number=number/i
i=i-1 #to check that factor again!
My question : Is it possible to change the last two line in a way that when I change i
and number
in the if
block, their value change in the for
loop!
Update: Defining the iterator as a global
variable, could help me? Why?
Solution
Short answer (like Daniel Roseman's): No
Long answer: No, but this does what you want:
def redo_range(start, end):
while start < end:
start += 1
redo = (yield start)
if redo:
start -= 2
redone_5 = False
r = redo_range(2, 10)
for i in r:
print(i)
if i == 5 and not redone_5:
r.send(True)
redone_5 = True
Output:
3
4
5
5
6
7
8
9
10
As you can see, 5
gets repeated. It used a generator function which allows the last value of the index variable to be repeated. There are simpler methods (while
loops, list of values to check, etc.) but this one matches you code the closest.
Answered By - matsjoyce
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.