0
num=int(input("Enter any number : -"))
for i in range(num):
    if(num <= 1):
        print("Please enter a number more than 1")

    elif(num%i ==0):
        print("The number is not a prime number")
        break
    else:
        print("The number is a prime number")
        break

However I have made a mistake as when I gave a value 0 or less than 1. It started showing an error.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • What is the actual question? Are you wondering why you don't get the correct result in general (your code does not check for prime numbers correctly) or why you get an error for numbers smaller than one? – Thomas Kühn May 31 '17 at 10:49
  • I don't see anything wrong ... can you edit your post with the error you get ? – Dadep May 31 '17 at 11:02

1 Answers1

3

There are many efficient ways to check if a number is prime.

Here, What is the best algorithm for checking if a number is prime?

However specific to your questions, there are a lot of errors:

1) The code fails due to Zero Divison Error because your range starts from 0, try

for in range(2, num)

since num %1 is always zero

2) if(num <= 1): should be outside for loop to avoid unnecessary looping

Here is the simple modified version of your script:

num = int(input("Enter any number : "))

def check_prime(num):
    if(num <= 1):
        print("Please enter a number more than 1")
        return

    # check if number is 2 or 3 as they are prime numbers
    if (num == 2 or num == 3):
        print("Number is prime")
        return

    # checking for number divisible by 2, 3 or 5 covers large set of numbers
    if (num % 2 == 0 or num % 3 == 0):
        print("Number is not a prime number")
        return

    # if none of the above case is satisfied then iterate to half of the number
    # as number more than half is never a factorial of the number
    for i in range(7, int(num / 2)):
        if(num % i == 0):
            print("The number is not a prime number")
            return
    print("Number is prime")


check_prime(num)

However, there are efficient solutions available.

Raj Subit
  • 1,487
  • 2
  • 12
  • 23