lundi 14 août 2017

Is it possibe to use 'else' with 'for' in python? [duplicate]

This question already has an answer here:

I was solving a quiz asked me to write a code that generates only prime numbers (2,3,5,7,11,...) My wrong code was :

def genPrimes():
    primes = []   # primes generated so far
    last = 1      # last number tried
    while True:
        last += 1
        for p in primes:
            if last % p == 0:
                break
            else:
            primes.append(last)
            yield last

when I chose to show the answer, the answer was like that :

def genPrimes():
    primes = []   # primes generated so far
    last = 1      # last number tried
    while True:
        last += 1
        for p in primes:
            if last % p == 0:
                break
        else:
                primes.append(last)
                yield last

The only difference is I wrote 4 additional spaces before 'else'. what I know is we use else with 'if' and 'try', But it's new to me to see else with 'for' and also it looks strange that the distance between 'else' and the block below it is 8 whitespaces instead of 4 !! can anyone tell me what's wrong with my code and when we use 'else' with 'for' and is it possible to add 8 whitespaces instead of 4 ??

Aucun commentaire:

Enregistrer un commentaire