write a program to check whether a number is prime or not in python

In this article let's try to check if input number entered is prime or not using the Python programming

 

write a program to check whether a number is prime or not in python

 

 

Write a program to check whether a number is prime or not in python

Let's ask a user to enter number

number = int(input("Enter a Number : "))




Initially let's assume the number entered is prime,  take A variable Prime flag and set it to true. Iterate from 2 to number / 2 And get the index.  Divide the number by index  if the number is completely divisible by index set the Prime flag to false, and exit for loop using break Statement.


prime_flag = True
for index in range(2, int(number /2 ) +1):
   if number % index == 0:
       prime_flag = False
       break




Finally check if the prime flag is true then print a number entered as the prime number, using else Statement print number is not a prime number.

if prime_flag:
   print("Number Entered is Prime Numbers")
else:
   print("Number Entered is Not a Prime Numbers")




Final program:

number = int(input("Enter a Number : "))

prime_flag = True
for index in range(2, int(number /2 ) +1):
   if number % index == 0:
       prime_flag = False
       break

if prime_flag:
   print("Number Entered is Prime Numbers")
else:
   print("Number Entered is Not a Prime Numbers")




Output 1:

Enter a Number : 22
Number Entered is Not a Prime Numbers



Output 2:

Enter a Number : 23
Number Entered is Prime Numbers



Conclusion:  Run the program by providing different number and check if they are prime or not.  comment down below if you have any queries

Post a Comment

0 Comments