Trial Division Prime Generator import math


def generate_primes(limit):
    """Generates and prints a list of primes up to a given limit"""
    prime_list = [2, 3]
    num = 5
    increment_2 = True  # When True increment by 2. When False increment by 4

    while num &lt;= limit:
        is_prime = True
        sqr_lim = math.sqrt(num)
        for x in prime_list:
            # Loop through list of prime numbers and check divisibility
            if x &gt; sqr_lim:
                break
            if num % x == 0:
                is_prime = False
                break

        if is_prime:
            # Add primes to list to only check prime numbers
            prime_list.append(num)

        # Alternate step size between 2 and 4 to skip multiples of 2 and 3
        if increment_2:
            num += 2
            increment_2 = False
        else:
            num += 4
            increment_2 = True

    print(prime_list)
    return prime_list


def main():
    generate_primes(200)


if __name__ == "__main__":
    main()


I'm writing a program to generate a list of prime numbers to a given limit through the use of trial division. I was wondering if there is a way to further optimize this code. Currently it: skips multiples of 2 and 3; stores primes in a list and the list is used to check for primality; and checks divisibility up until the square root of the number it's analyzing.

I would also appreciate it if someone could critique me on my coding style such as comments, white space, and organization because I know its pretty rough around the edges. Thanks for the help.
The function generate_primes() shouldn’t print the list it generated.  The caller should print the returned value, if desired. 



Calling generate_primes(2) will unexpectedly return [2, 3], as will generate_primes(1) or generate_primes(-500).



The increment_2 flag is awkward.  When True, increment by 2 seems ok, but when False the increment is ... what?  0?  1?  

Instead of an increment_2 flag, you could use an increment amount, starting with 2 ...

increment = 2


... and then toggle that value between 2 &amp; 4:

num += increment

# Alternate step size between 2 and 4
increment = 6 - increment


No more if ... else ..., reducing the complexity of the function slightly. 



Stretch goal:

After generate_primes(200), if a call is made to generate_primes(500), you will recalculate all of the primes beneath 200.  Perhaps there is a way to cache the computed values for future generate calls?