0

I have the following function:

def prime(number):
    for num in range(1,number):
        if num > 1:
            for i in range (2, num):
                if (num%i == 0):
                    return("not a prime")
            else:
                return(num)

print(prime(9))

Output: 2

Please explain where I am doing a mistake or how can I get a list of all prime numbers in any input range ex:-9 or 100 or 300.

lmiguelvargasf
  • 40,464
  • 32
  • 169
  • 172

1 Answers1

4

The problem is that when you reach the return statement, the function execution terminates, so you will only get the first prime. Consider creating a list in which you will append your prime numbers as follows:

def prime(number):
    primes = []
    for num in range(1, number + 1):
        if num > 1:
            for i in range (2, num):
                if (num % i == 0):
                    break
            else:
                primes.append(num)
    return primes

This will give you the prime numbers from 2 up to number. I hope this helps you.

As suggested by @jpp, you can also use yield as follows:

def prime(number):
    for num in range(1,number):
        if num > 1:
            for i in range (2, num):
                if (num%i == 0):
                    break
            else:
                yield num

for num in prime(20):
    print(num)
lmiguelvargasf
  • 40,464
  • 32
  • 169
  • 172