First Program Bug (Newbie)

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 18 02:33:53 CET 2008


On 17 mar, 21:03, Benjamin Serrato <benjamin.serr... at gmail.com> wrote:

> I Found It!! The following was a post asking for help finding a bug. I
> thought I needed help with my syntax, but just before sending I found
> the bug on line 13. Line 13 should read: "base = 2". I would still
> appreciate any comments on my program. Maybe there is a better way to do
> it that I didn't think about. I know it's not that interesting but it's
> my first one.

You may look at the fact.py demo script (somewhere in your python
installation)

> I'm almost halfway through an online tutorial I found on the python.org
> site and decided to stop and write a program for myself. I got it in my
> head to write a program to print all the primes; the idea came from
> another tutorial. The program prints some non-prime numbers. In a
> comparison to lists of primes the program prints eight non-primes for
> numbers less than 150. Those numbers are [27,35,87,95,119,123,143,147].
> Here is the program.
>
> base = 2
> candidate = 3
>
> while True:
>         while candidate % base != 0:
>                 base = base + 1
>                 if base > (candidate / 2):
>                         print candidate
>                         candidate = candidate + 1
>                         base = 2
>         else:
>                 candidate = candidate + 1
>                 base = 2 # added

Note that you can increment candidate by 2 (starting at 3, all primes
are odd numbers). And after testing 2, you can increment base by 2
also.
And you can exit somewhat earlier: if base*base>candidate there is no
point in keep trying (now you`re exiting when base*2>candidate)

> At first I tried to use 'return' on the 'else' block to cause the
> program to loop, but I don't understand 'return' yet and that didn't
> work. So, I put the rest into another while loop and was really happy to
> find it worked but the program prints some non-prime numbers.

return only makes sense inside a function. Wait until the next
lesson...

--
Gabriel Genellina



More information about the Python-list mailing list