Python Program to check Prime Number

Python Program to check Prime Number





In this exercise, we will be creating a program to check whether a number is prime number or not. For this we will take a number input from user which he wants to check for prime.

Logic and Explanation

Then we will make a loop and will divide that number with all the numbers less than that number except 1. If any number divides it completely without leaving remainder then it is not prime and if it does not get divided by any number then it is a prime number

I hope the logic for question would be clear to you. You are advised to try it first and then check the program source code which is given below.

You can run and code in python online on this website - Python Online Interpreter

Source Code

n= int(input("Enter a number"))
for x in range(2,n):
    if n%x==0:
        break
if x+1==n:
    print (n,"is a prime number")
else:
    print (n,"is not a prime number")

Output

Enter a number571
571 is a prime number
Enter a number267
267 is not a prime number


If you like the content, share it in your social media platforms so that we can help the maximum. If you have any query then feel free to ask in the comments below.
We are ready to help you.
Enjoy Coding!!

2 Comments

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

  1. Can you explain why you given x+1==n after break statement?. I couldn't get it

    ReplyDelete
    Replies
    1. If any number from 2 to n-1 divides n then it is not prime as for prime it should have only two factors 1 and n.
      So, if loop is breaked then it means that it is not prime and if loop does not break then the value of x at the end of loop will be n-1.
      So, by writing x+1 = n, I am checking that whether loop has breaked somewhere or not.

      Delete

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

Previous Post Next Post