Python: for loops and xrange() -
this question has answer here:
- scope of python variable in loop 7 answers
i learning python , came across 'for loop' let's have program asks 5 numbers. know it's pointless it's example. anyway, if did this, wouldn't restart cycle.
mynumbers = [] x in xrange(5): try: mynumbers.append( int(raw_input()) ) except valueerror: mynumbers = [] x = -1
i thought if had reset x -1 make loop go on more, never restarted. still only went 5 times. reason why put -1 there because x count 0 right after that. tried find solutions, there weren't any. thank if try me.
xrange()
(or range()
) called generator functions, x local variable
loop assigns next value in loop to.
xrange()
returns values in range given in parameters 1 1 , , loop assigns variable x. if change value of x within loop, xrange() has no idea such change , still provide next value in range.
example of generator functions -
def myrange(a): = 0 while < a: yield = + 1 >>> x in myrange(10): ... print(x) ... x = 1 ... 0 1 2 3 4 5 6 7 8 9
the value change in x
never propagated range()
or xrange()
function.
Comments
Post a Comment