1

I have written a code to check for the total number of prime numbers up to and including a certain no. When performing the check for the given number as 3, a change in the indentation of the else statement is changing my output. I cannot understand why is that happening; please explain. I need output as [2,3].

def count_prime(num):
    lis=[x for x in range(3,num+1,2)]
    lisi=[2]
    check=False
    if num==0 or num==1:
        return 0
    for a in lis:
        for b in range(3,a,2):
            print(b)
            if a%b==0:
                check=False
                break
            else:
                print('here is indentation change')
                check=True
                pass
        if check==True:
            lisi.append(a)
    primes=len(lisi)
    print(lisi)
    return (primes)

This gives the list of primes as 2 and no. of primes=1 for num=3

def count_prime(num):
    lis=[x for x in range(3,num+1,2)]
    lisi=[2]
    check=False
    if num==0 or num==1:
        return 0
    for a in lis:
        for b in range(3,a,2):
            print(b)
            if a%b==0:
                check=False
                break
        else:
            print('here is indentation change')
            check=True
            pass
        if check==True:
            lisi.append(a)
    primes=len(lisi)
    print(lisi)
    return (primes)

This gives the list of primes as [2,3] and no. of primes=1 for num=3

Please click the below links to see the images of the codes

output is 2,3.

output is 2.

MAYUR
  • 11
  • 3
  • 3
    Welcome to Stack Overflow. Please include your code as text and not as an image. – ewokx May 22 '22 at 08:15
  • 1
    Because in Python scopes are based on indentation. In the first one the `else` is on the `if`, in the second one its on the `for`. https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – Guy May 22 '22 at 08:17
  • `for`/`else` is also a construct in python – roganjosh May 22 '22 at 08:19
  • After you indent (left) the *else* now pertains to *for* (yes - there is an infrequently used for/else construct) so it completely changes your logic – DarkKnight May 22 '22 at 08:20

1 Answers1

0

The else block with loops (after the for/while block) is executed if there was no exit with the break statement inside the loop.

Vadim Sid
  • 1
  • 3