My backwards logic

Juan Christian juan0christian at gmail.com
Fri Sep 5 13:35:48 EDT 2014


I made this code just for fun and learning, it's working, but would this be
a good approach? Thanks.

import sys


def prime_checker(start = 1, stop = 1):
for number in range(start, stop + 1):
divisors = [(number % x) for x in range(1, number + 1)]
print("{n} prime? {r}".format(n = number, r = (divisors.count(0) == 2)))


if __name__ == '__main__':
prime_checker(int(sys.argv[1]), int(sys.argv[2]))


On Fri, Sep 5, 2014 at 2:17 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:

> On Fri, Sep 5, 2014 at 11:08 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> > Python's 'for' loop has a handy 'else' extension which is perfect for the
> > search-type of 'for' loop:
> >
> >    while True:
> >         a=random.randrange(1,8)
> >         print (a)
> >         for x in range(2,a):
> >             if a%x==0:
> >                 print ("Number is not prime")
> >                 break
> >         else:
> >             print ("Number is prime")
> >         wait = input (" "*40  + "Wait")
> >
> > Note the two lines I added after the 'break' and before the 'wait'.
>
> Also note that this construct tends to be particularly sensitive to
> indentation. If you accidentally indent the else block one level too
> many (which your editor may well do for you to "helpfully" match it up
> with the if), then you'll get a completely different result.
>
> I would not worry about the else clause as a beginner, as it's
> relatively unique to Python and tends to be somewhat confusing. Use a
> flag or refactor the function instead.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140905/d1266ec1/attachment.html>


More information about the Python-list mailing list