My backwards logic

Chris Kaynor ckaynor at zindagigames.com
Fri Sep 5 13:09:05 EDT 2014


On Fri, Sep 5, 2014 at 9:48 AM, Seymore4Head <Seymore4Head at hotmail.invalid>
wrote:

> I'm still doing practice problems.  I haven't heard from the library
> on any of the books I have requested.
>
>
> http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
>
> This is not a hard problem, but it got me to thinking a little.  A
> prime number will divide by one and itself.  When setting up this
> loop, if I start at 2 instead of 1, that automatically excludes one of
> the factors.  Then, by default, Python goes "to" the chosen count and
> not "through" the count, so just the syntax causes Python to rule out
> the other factor (the number itself).
>
> So this works:
> 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
>     wait = input (" "*40  + "Wait")
>
> But, what this instructions want printed is "This is a prime number"
> So how to I use this code logic NOT print (not prime) and have the
> logic print "This number is prime"
>
>
One neat feature of Python is the for...else function. The code inside the
else block will run only if the loop ran to completion (untested code
follows):

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")


Depending on how advanced you want to get (I know you are relatively new to
Python), another decent way would be to extract the prime check to a
function, and return the result, and print based on that result (again,
untested code):

def isPrime(number):
    for x in range(2,a):
        if a%x==0:
            return False
    return True

while True:
    a=random.randrange(1,8)
    print (a)
    if isPrime(a):
        print("Number is prime")
    else:
        print("Number is not prime")
    wait = input (" "*40  + "Wait")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140905/430bcb1d/attachment.html>


More information about the Python-list mailing list