List previous prime numbers of n
<p>I am trying to create a program in python that takes a number and determines whether or not that number is prime, and if it is prime I need it to list all of the prime numbers before it. What is wrong with my code?</p>

<pre><code>import math
def factor(n):
    num=[]
    for x in range(2,(n+1)):
        i=2
        while i&lt;=n-1:
            if n % i == 0:
                break
            i = i + 1
        if i &gt; abs(n-1):
            num.append(n)
            print(n,"is prime",num)
        else:
            print(i,"times",n//i,"equals",n)
    return
</code></pre>

<p>Your method only returns whether the 'n' is prime or not.
For this purpose, you don't need a nested loop. Just like this</p>

<pre><code>def factor(n):
    num=[]
    for x in range(2,(n+1)):
        if n % x == 0:
            break
    if x &gt; abs(n-1):
        num.append(n)
        print(n,"is prime",num)
    else:
        print(x,"times",n//x,"equals",n)
    return
</code></pre>

<p>And then, if you want all the other primes less than n, you can use prime number sieve algorithm.</p>

<p>--------- Update --------------</p>

<p>A modification of your code which can find the other primes (but prime sieve algorithm still has better performance than this)</p>

<pre><code>def factor(n):
    num=[]
    for x in range(2,(n+1)):
        i=2
        while i&lt;=x-1:
            if x % i == 0:
                break
            i = i + 1
        if i &gt; abs(x-1):
            num.append(x)
    if n in num:
        print num
    else:
        print str(n) + ' is not num'
    return
</code></pre>

python prime-factoring