0

I've tried running this python script but it returns an empty list, I don't see what I'm missing but it seems I'm failing to append anything to the list. (The goal is to return a list of n numbers of prime numbers starting from 2, there are restrictions such as using only the while loop.) Appreciate any insights!!

def primes_list(n):
    primes = []
    count = 0
    while count < n:
        num = 1
        divisor = 2
        while num % divisor != 0 and num > divisor:
            divisor += 1
        if divisor == num:
            primes.append(num)
        count += 1
    return primes
  • [How to step through Python code to help debug issues?](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues) – Luuk Oct 03 '22 at 06:10
  • The while statement `num % divisor` always uses `1 % 2` which is always 1, but `num > divisor` is never true, so divisor never changes. Then `if divisor == num` is alsways doing `if 2 == 1`, which is never true. – Luuk Oct 03 '22 at 06:14
  • Thanks @Luuk you're completely right. – user19919932 Oct 03 '22 at 06:23
  • Which is what "every time around, the two boolean conditions are both false" means in my answer below. See also there for the root cause of the problem, since the conditions themselves look correct. – polo-language Oct 03 '22 at 06:45
  • Is this to create list of primes within n range or until n element is fulfilled? – Arifa Chan Oct 03 '22 at 07:50

3 Answers3

0

count is not used in the algorithm. Do you mean to use count everywhere num currently appears? Since you reset num to 1 on every iteration, every time around, the two boolean conditions are both false and the outer while effectively just counts up to n.

polo-language
  • 826
  • 5
  • 13
0

You don't need count as a counter. You just need to move num outside the while loop and increase num till n.

def primes_list(n):
    primes = []
    num = 1
    while num < n:
        divisor = 2
        while num % divisor != 0 and num > divisor:
            divisor += 1
        if divisor == num:
            primes.append(num)
        num += 1
    return primes
Arifa Chan
  • 947
  • 2
  • 6
  • 23
0
def primes_list(n):
    num = 1
    while num <= n:
        div = 2
        while num % div and num > div: div += 1
        if div == num: yield num
        num += 1

print(list(primes_list(100)))

This will simplify the code and alternative using yield generator.

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]