Table of Contents

Check If a Number is Prime or Not | Pictoblox

Example Description
This Python program checks whether a given number is prime or not. If the number is less than or equal to 1: we need to execute again!"

Introduction:

In this Python program, we take a number as input from the user and check whether it is a prime number or not. We assume that the number is a prime number by default and then iterate from 2 to half of the number. If the number is divisible by any of the iterations, we flag it as not prime. Finally, we output whether the number is prime or not.

Code:

#Write a Python program to check if a given number is prime or not.
num = int(input("Enter the number to be checked: "))
flag = 0 #presume num is a prime number
if num > 1 :
 for i in range(2, int(num / 2)):
  if (num % i == 0):
    flag = 1 #num is a not prime number
    break #no need to check any further
 if flag == 1:
  print(num , "is not a prime number")
 else:
  print(num , "is a prime number")
else :
 print("Entered number is <= 1, execute again!")

Logic:

  1. Take a number as input.
  2. Assume the number is a prime number (flag = 0).
  3. Check if the number is greater than 1.
  4. If yes, iterate from 2 to half of the number.
  5. If the number is divisible by any iteration, update the flag to 1 (not prime) and break the loop.
  6. After the loop, check the flag value:
    a. If flag is 1, print that the number is not a prime number.
    b. If flag is 0, print that the number is a prime number.
  7. If the number is less than or equal to 1, print a message asking the user to enter a different number.

Output:

Enter the number to be checked: 5

>> 5 is a prime number

 

Enter the number to be checked: 9

>> 9 is not a prime number

 

Enter the number to be checked: 1

>> Entered number is <= 1, execute again!