0

I am starting out in Python and have a question about the following piece of code:

def prime2(n):
    n = eval(input("What is your number? "))
    for i in range(2, int(math.sqrt(n)) + 1):

        if n % i == 0:
            return False
        else:
            return True

So when True is returned, n is prime. Now is there a way to list all the values of n for which the if statement is true?

2
  • You don't have to evaluate input(), it gets evaluated to a python value automatically. Commented Feb 28, 2011 at 16:03
  • 4
    just a note - you should return True outside for, otherwise the loops is meaningless Commented Feb 28, 2011 at 16:08

2 Answers 2

4

Since there is an infinite amount of prime numbers, no. However, you can list all primes in a certain interval:

foo = [x for x in range(1000) if prime2(x)]

This gives you a list of all primes in the interval 0 to 1000.

Edit: Why do you have n as parameter to your function, and then read it as input from the user? This discards the argument that was passed to the function. Input from the user should be outside of that function. The script could look like this:

def prime2(n):
    for i in range(2, int(math.sqrt(n)) + 1):

        if n % i == 0:
            return False

    return True

max = int(input("What is your number? "))
print [x for x in range(max) if prime2(x)]

Edit2: Fixed the code of prime2 according to @rmflow's comment to the question.

Sign up to request clarification or add additional context in comments.

Comments

0

if you need a list of all values when n is a prime then you need a prime number generator. An example (not effectuve though) based on your prime2 function:

import math

def prime2(n):
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

def prime_generator():
    n = 1
    while True:
        n += 2
        if prime2(n):
            yield n

primes = prime_generator()

for prime in primes:
    print prime

will print prime numbers until break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.