[Tutor] Program to find if a number entered by user is a prime number or not
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Oct 16 04:40:48 EDT 2020
On 16/10/2020 02:30, Manprit Singh wrote:
> 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)
This is bad on several counts.
The biggest issue is that you do the call to all() before checking if
the no is <2 which is a huge wasted effort.
Much better to put the check for <2 before calling all()
Also pass does nothing so there is no need to have
else: pass
just leave off the else.
And if you have pass in an if and code in the else that means you should
probably invert the if condition.
> Just need to know if my way of implementing the problem is correct ? Can
> this program be further optimised ?
Its very convoluted. I notice you have now pasted two better solutions.
I'll comment on them separately.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list