My backwards logic

John Gordon gordon at panix.com
Fri Sep 5 19:08:05 CEST 2014


In <1enj0att6bkrnvb81rhma5dbuk3h28agl8 at 4ax.com> Seymore4Head <Seymore4Head at Hotmail.invalid> writes:

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


There are two basic tactics you can use:

1. Initialize an "isprime" flag to True at the top of the while loop.  
   In the for loop, replace the print statement with a statement that
   sets isprime to False.  After the for loop, insert a check on isprime,
   and print "This number is prime" if isprime is still True.

2. Create a separate function just for testing if a number is prime, which
   returns True or False.  Then call that function within your while loop.

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list