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

prime numbers in python same programs different outputs

I have this assignment where I have to write a code to determine if a number is a prime number or not and I couldn’t come up with a solution so I searched the net and found the following code( the first one) and then I wrote the exact same code but with a different name and it didn’t work for numbers like 65, 75, … and said they are prime numbers, while they aren’t.
Can you help me find out what I’m doin wrong!
thank you in advance!

The code I copied:

    num=int(input())
if num > 1:
    for i in range(2, int(num/2)+1):
        if (num % i) == 0:
            print(num, "is not a prime number")
            break
    else:
        print(num, "is a prime number")
  
else:
    print(num, "is not a prime number")

my code:

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

addad=int(input())
if addad>1:
    for i in range(2,int(addad/2)+1):
        if (addad%i)==0:
            print("not prime")
            break
        else:
            print("prime")
            break
else:
    print("prime")

>Solution :

They are not same.

In the above code you use for...else but in the second you used if...else. Take a closer look at the indentations. White space has great significance in python.

I think you might need to read a little about for/else in python. You will find the difference for sure.

little description, else in the same indent with for will run if the for loop goes to the end(no breaks). so in the first snippet else will run at the end of the for with condition of no breaks happening, while in the code that you write else is IN the for block and will run in each cycle and it is bind to the if command above.

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