As a homework I have to write a prime number test, that gives back a "true" or "false" statement. The tricky thing is, I have to write a csv.-file that includes the "true" and "false" statements for the numbers 1 to 1000. I used this code for the prime number test
def Primzahl(n):
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
and
for i in range (1,1001):
Primzahl (i)
print (i)
My for-loop only gives out the numbers 1,1000 but not the true or false statements. Do I have to include if and else in my for loop? Can anyone help?
The problem is print(i)
. That will write i
, which is the number from your range
call. You will also need to print the value returned by your function, eg print(Primzahl(i))
.
Currently you're only printing i, and not the return value from your method. You aren't doing anything with the return value from your method. You should assign the result to a variable and print the variable also. (You could also just call the method from within the print statement.)
for i in range (1,1001):
isPrime = Primzahl(i)
print (i + ": " + isPrime)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.