-1

I'm new to python. I just tried to write a basic program (to check whether a number is prime or not). I referred the code from an online site and tried to write one myself.

The code is as follows:

#PYTHON PROGRAM TO CHECK PRIME NUMBER
print("Enter a number :: ", end = " ")
num = int(input())

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

else:
    print(str(num) + " is neither prime nor composite.")

The doubt I have is in the working of the code. It runs without any errors and produces the correct output as well.

The confusing code snippet is:

for i in range(2,int(num/2)):
    if(num%i) == 0:
        print(str(num) + " is not prime")
        break;
else:
    print(str(num) + " is prime")

EDIT: Why is there an else after the for loop and not after the if statement? Could someone please explain?

5unfl0w3r
  • 1
  • 4

1 Answers1

0

Essentially this for loop checks all numbers contained from 2 to the half of the input number. If any numbers along the way yield a perfect division with no remainder (ex. 4%2 = 0) then it breaks. The % operator gives you the remainder of an int division (ex. 5%2 = 1). Hence for a prime number there should always be a remainder, since no perfect division should be possible in the specified range. If there is no remainder then the code breaks the loop and classifies this number as not prime.

  • 1
    I think OP understands the logic. `for..else` is the part which is confusing to OP and many others. – mad_ Apr 07 '20 at 16:55