Search code examples
pythonbreakcontinue

Prime number(Python 3)


My goal is to build a programm, that says is a number prime or not. A positive whole number n > 2 is prime if no number between 2 and sqrt(n) divides n.

Here is my code:

import math

def main():
     print("Prime number or not")
     try:
          N = -1
          while N<2:
              print("Error!Enter numbers greater than two")
              N = int(input("Enter the right number:"))
              values = list(range(2,round(math.sqrt(N))))
              for i in values:
                  if i%N !=0:
                      continue
                  x = print("The number is not prime")
                 elif i%N ==0:
                     break
                 x = print("The number is NOT prime")
           print(x)

    except ValueError:
        print("Error!Print correct number")
    except NameError:
        print("Error!Print the numbers")

main()

But is shows a syntax error in line

elif i%N ==0:

Please, give me some advice how to correct this error and about the code in general. I am new in learning Python, so any help and critic will be good! Thanks.


Solution

  • If you wanted this to be your whole programme, here is my solution:

    # Get num
    num = input('Input a whole number: ')
    
    # Is num valid
    try:
      num = int(num)
      if num < 1 or num > 1000000000000:
        print('Your field cannot be greater than one quantillion or less than one.')
      else:
        # Is num 2 or 5, if yes, prime.
        if num != 2 and num != 5:
          # Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
          lastNum = str(num)[-1]
          if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
            print('Your number is composite.')
            if lastNum == '5':
              print(str(num) + ' is divisible by 5.')
            else:
              print(str(num) + ' is divisible by 2.')
          else:
            # List multiples of 3 less than 123, call it multiplesOf3.
            multiplesOf3 = []
            appendMultiple = 0
            for i in range(40):
              appendMultiple += 3
              multiplesOf3.append(appendMultiple)
            # Get sum of all numbers in num, name is sumOfNum
            sumOfNum = 0
            numStr = str(num)
            for i in range(len(numStr)):
              sumOfNum += int(numStr[i])
            # Is sumOfNum in multiplesOf3? 
            numMultipleOf3 = sumOfNum in multiplesOf3
            if numMultipleOf3 == True:
              print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
            else:
              print('Your number is prime.')
        else:
          print('Your number is prime') 
    except:
      print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
    

    But if you wanted this to be just a function, here is my solution (Make sure you put in a parameter, it requires 1 argument; put in your number.)

     def isPrime(num): 
      try:
        num = int(num)
        if num < 1 or num > 1000000000000:
          print('Your field cannot be greater than one quantillion or less than one.')
        else:
          # Is num 2 or 5, if yes, prime.
          if num != 2 and num != 5:
            # Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
            lastNum = str(num)[-1]
            if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
              print('Your number is composite.')
              if lastNum == '5':
                print(str(num) + ' is divisible by 5.')
              else:
                print(str(num) + ' is divisible by 2.')
            else:
              # List multiples of 3 less than 123, call it multiplesOf3.
              multiplesOf3 = []
              appendMultiple = 0
              for i in range(40):
                appendMultiple += 3
                multiplesOf3.append(appendMultiple)
              # Get sum of all numbers in num, name is sumOfNum
              sumOfNum = 0
              numStr = str(num)
              for i in range(len(numStr)):
                sumOfNum += int(numStr[i])
              # Is sumOfNum in multiplesOf3? 
              numMultipleOf3 = sumOfNum in multiplesOf3
              if numMultipleOf3 == True:
                print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
              else:
                print('Your number is prime.')
          else:
            print('Your number is prime') 
      except:
        print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
    

    Another way,

    def isprime(n):
      if min(n//2,n//3,n//5) == 1:
        return True
      elif min(n%2,n%3,n%5) == 0:
        return False
      return True
    

    This is SO much shorter!