How do 'for in' loops work in python? -
i'm new python (after c, c++). learning fine until got stuck @ 'for x in' loops. specific take example in program lists prime numbers:
num in range(10,20): in range(2,num): if num%i == 0: j=num/i print ('%d equals %d * %d' % (num,i,j)) break else: print (num, 'is prime number')
what happening in first 2 lines of code? how code flowing? please elaborate.
for num in range(10,20):
this creates range object (representing numbers 10 19 inclusive) , num
iterates through it
in range(2,num):
this creates range
object (representing numbers 2 num-1
inclusive) , i
iterates through it
much same as:
for (int num = 0; num < 20; ++num) { (int = 2; < num; ++i) {
in c-like languages, , no more ambiguous.
at end of loop, else
clause run if loop didn't encounter break
statement.
Comments
Post a Comment