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
el开发者_C百科se:
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?
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.
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
精彩评论