-1

I aim is to have a simple logic to find prime numbers between 2 ranges. However to start simple, i am trying to have a code that evaluates a number input if it is prime and i am failing at it. Though i am able to evaluate it to some degree the final print statement is off. How do i ensure that the final print only happens when the previous loop is done and did not succeed?

n = int(input ('The number'))
if n <2:
  print (n,' is not a prime number')
elif n==2:
  print (n, ' is a prime number')
else:
  i = 2
  while i<n:
    if n%i ==0:
      print (n, ' is not a prime number')
      break
    else:
      i +=1
print (n, " is a prime number")    
Vish
  • 9
  • 5
  • Possible duplicate of [Checking if a number is a prime number in Python](https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python) – quamrana Dec 03 '17 at 18:35
  • I believe you should have a look at this algorithm to find all primes up to N: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes – Olivier Melançon Dec 03 '17 at 18:37

2 Answers2

0

In this case, you could use the while-else construction.

See https://docs.python.org/3/reference/compound_stmts.html#the-while-statement

(Or https://docs.python.org/2/reference/compound_stmts.html#the-while-statement if you are using python 2.7)

Peter Pesch
  • 643
  • 5
  • 14
  • Thank you vvv much Peter. your clue helped me solve in few seconds and very thankful.n = int(input ('The number')) t = True if n <2: print (n,' is not a prime number') elif n==2: print (n, ' is a prime number') else: i = 2 while i – Vish Dec 03 '17 at 18:43
0

Well, you can find this answer anywhere on the net. But i will put a simple function here to check for a prime number.

def is_prime(num):
    """ Returns if the given number is prime or not
    """ 
    # 0 and 1 are not a prime numbers so return them as not a prime number
    if num == 0 or num == 1:
        return '{0} is Not a prime number'.format(num)
    for i in range(2, num):
        if num%i == 0:
            return '{0} is Not a prime number'.format(num)
    return '{0} Is a prime number'.format(num)

n = int(input ('The number'))
print(is_prime(n))
Manjunath
  • 150
  • 1
  • 6