Python Program to check if a number is prime or not using While, For Loop and IF Condition
Scenario :Suppose we a have the requirement to check whether a Number, provided as user input, is a Prime Number or Not. Also we need to make sure, user should enter a number >1, and should not enter a string.
To handle input exceptions, we have used the try..except blocks in the Code.
# 1. Python Program to check if a number(>2) is prime or not with exception handling :
flag1 = False
flag2 = None
num = None
while (flag1 == False):
try:
num = int(input("Please enter a Number > 2: "))
flag1 = True
if num > 1:
for i in range(1, num):
if (num % i == 0):
flag2 = True
break
else:
print("Try again: Invalid Input")
flag1 = False
except ValueError as e:
print("Error Message: Please enter a Numer > 2\nError Details: ", e)
if flag2 == True:
print("The number is not Prime")
else:
print("The number is a Prime")
# ------------------------------------------------------------------------------------------------------------------------ #
Exception Testing Scenarios : # Input : ab
# Output :
Error Message: Please enter a Numer > 2
Error Details: invalid literal for int() with base 10: 'ab'
Please enter a Number > 2:
# Input : if you give the input either 0 or 1
# Output :
Try again: Invalid Input
Please enter a Number > 2:# ------------------------------------------------------------------------------------------------------------------------ #
Notes :
To handle the above exception Scenarios, we have used the try...except blocks. With use of While loop we can repeat the process as along as the user enters the correct input.
The While loop will exit once the flag1 = True , when there is no exception in try block.
Please take care the Code Indentation or blocks, the suit of the same of statements to execute in order by Python Interpreter.
Python version : 3.10
# ------------------------------------------------------------------------------------------------------------------------ #
# 2. Python Program to check whether a Number(>1) is Prime or Not :
# The following is a simple method to check any Number(>1) is Prime or Not.
n = int(input("Enter a Number >1 to check if it is Prime or Not: "))
i = 0
k = 0
for i in range(1, n+1):
if n % i == 0:
k = k + 1
if k == 2:
print('The Number {0} is Prime'.format(n))
k = 0
else:
print('The Number {0} is Not Prime'.format(n))
# ------------------------------------------------------------------------------------------------------------------------ #
Input:
Enter a Number >1 to check if it is Prime or Not: 2
Output:
The Number 2 is Prime
# ------------------------------------------------------------------------------------------------------------------------ #
No comments:
Post a Comment
Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.