Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

checking for prime number, why does my output not include 2?

def is_prime(num):
    for i in range (2, num):
        if num % i == 0:
            return False
        else:
            return True
        

for i in range(1, 20):
    if is_prime(i + 1):
        print(i + 1, end=" ")
print()

I think it has something to do with the range function and value of 2 in the lower code?

expected output – 2 3 5 7 9 11 13 15 17 19

my output – 3 5 7 9 11 13 15 17 19

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For is_prime(), when num = 2, the for loop is skipped entirely and the function returns None. None is a falsy value, so 2 is never printed.

Here is an is_prime() implementation that resolves this issue:

def is_prime(num):
    for i in range(2, num):
        if num % i == 0:
            return False
    return num != 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading