Python prime numbers

Dave Angel davea at davea.name
Sat Feb 1 17:07:56 EST 2014


 Panagiotis Anastasiou <panast24 at gmail.com> Wrote in message:
> Hi i'm new in programming and in python and i have an assignment that i cant complete. I have to Write a Python program to compute and print the first 200 prime numbers. The output must be formatted with a title and the prime numbers must be printed in 5 properly aligned columns . I have used this code so far :
> 
> numprimes = raw_input('Prime Numbers  ')
> count = 0
> potentialprime = 2
> 
> def primetest(potentialprime):
>     divisor = 2
>     while divisor <= potentialprime:
>         if potentialprime == 2:
>             return True
>         elif potentialprime % divisor == 0:
>             return False
>             break
>         while potentialprime % divisor != 0:
>             if potentialprime - divisor > 1:
>                 divisor += 1
>             else:
>                 return True
> 

There are several things wrong with this function,  and it's
 redundant enough that maybe none of them matter.  I'd test it
 carefully. 

> while count < int(numprimes):
>     if primetest(potentialprime) == True:
>         print potentialprime
>         count += 1
>         potentialprime += 1
>     else:
>         potentialprime += 1
> 
> but i get the result in a single column . How can i get it in 5 rows? Can someone help please
> 

As has been pointed out,  you can use a trailing comma to suppress
 the implied newline for each print. 
Then you can add it back in every five items by checking count.

But you have a bigger problem,  lining up the columns.  Try using
 the string modulus operator, or 'format'.

-- 
DaveA




More information about the Python-list mailing list