Sage Ambroski
Sage Ambroski

Reputation: 11

Are nested for loops possible in python?

I am working on a program that finds prime numbers in order to learn about for loops. I have a list of some primes that can be used to check % == 0. I've tried this

primes = [1, 3, 5, 7, 9, 11, 13, 17, 19, 29]
hold_the_primes = []
for x in range(29,841):
    for y in primes:
        if x % y == 0:
            pass
        else:
            hold_the_primes.append(x)
primes.extend(hold_the_primes)
for x in primes:
    print x

but it returns nothing and the terminal gets stuck at this point. What can I do to accomplish this?

Upvotes: 0

Views: 122

Answers (1)

banshee.handset
banshee.handset

Reputation: 56

Nested loops are possible in python. The problem is with your code I believe.

Here are some pointers:

  • 1 is not prime, and your list should start with a 2 instead. You're also missing 23.
  • It looks like you are assuming if a number isn't evenly divisible by a prime number, it's prime. I don't think that's the proper check. For instance, if x = 29, hold_the_primes.append(x) will be called for when y = 3, 5, 7, 9, 11, 13, 17, and 19.
  • A number is prime if it has no other factors besides 1 and itself
  • (Edit) If all you did was move the second for loop into a function, I think you will see that your code is not behaving as expected

Here's an example that would work I believe:

primes = [2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29]
hold_the_primes = []

def isPrime(n):
    temp = 2;
    while temp*temp <= n: #temp < math.sqrt(n):
        if n % temp == 0:
            return False
        temp += 1
    return True

for x in range(30,841):
    if isPrime(x):
        hold_the_primes.append(x)


primes.extend(hold_the_primes);
for x in primes:
    print x

Upvotes: 1

Related Questions