[Tutor] Program to find if a number entered by user is a prime number or not
Manprit Singh
manpritsinghece at gmail.com
Thu Oct 15 21:30:54 EDT 2020
Dear Sir ,
I was trying to write a program which allows the user to input a number
from a keyboard , it then prints the message x is prime if number input by
user is a prime number and x is not prime if the number input by user is
not a prime number. (here x represents the number). The program is written
below:
x = int(input("Enter any positive number"))
a = "not prime"
if all(x%i for i in range(2, int(x**0.5) + 1)):
if x < 2:
pass
else:
a = "prime"
else:
pass
print(x,"is",a)
I have these questions in my mind :
1) If you can see I have used pass two times , Initially I have assigned a
string "not prime" to variable a . Now if user input is either 0 or 1 , it
is not a prime number. That's why i have written a pass inside the below
written block, which will maintain a = 'not prime" when user input is
either 0 or 1.
if all(x%i for i in range(2, int(x**0.5) + 1)):
if x < 2:
pass
for any value of user input greater than 1 if the iterable inside all( )
is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the
user input for sure is a prime number , and hence i have assigned a =
"prime" inside that block.
Again for the second time i have used pass when all(x%i for i in range(2,
int(x**0.5) + 1)) returns False, in that case the number input by user is
again not a prime number , and hence i have used pass again in the block to
maintain the old value of variable a ="not prime".
Just need to know if my way of implementing the problem is correct ? Can
this program be further optimised ?
Regards
Manprit Singh
More information about the Tutor
mailing list