Why doesn't this work (Python)?
So I'm trying to learn Python using some tutorials, and I decided to create my own exercise. I wanted to create a script that figures out how many prime numbers there are between 1 and 1000, as well as printing the prime numbers. This is what I have so far:
numberlist = []
a = 1
prime = True
while a < 1000:
a = a + 1
for divisor in range(2,a):
if a/divisor==int(a/divisor):
prime=False
if prime == True:
print a
numberlist.append(a)
print "Number of prime numbers between 1 and 1000:", len(numberlist)
However, when I start the application, it returns
"Number of prime numbers between 1 and 1000: 0"
I don't know what I've done wrong. Can someone please clarify what I screwed up on?
Thank you for your help.
Edit: So now the code looks like this, but the same problem is occurring:
numberlist = []
a = 1
for a in xrange(1, 1000):
for divisor in range(2,a):
if a % divisor == 0:
prime=False
else:
prime=True
if开发者_StackOverflow中文版 prime == True:
print a
numberlist.append(a)
print "Number of prime numbers between 1 and 1000:", len(numberlist)
There are a number of problems with this code. First, a/divisor == int(a/divisor)
is always True
, because division in Python is integral (you will always get an integer result). Use a % divisor == 0
instead.
Another problem is that prime = True
is outside the loop, meaning that as soon as one value is declared not prime, no more values can be prime! (prime
will never get set back to True
anywhere.)
A third issue, more of style, is that it is preferred to use a for ... in
loop in python, eg
for a in xrange(1, 1000):
for divisor in xrange(2, a): ...
Edit: Regarding your modified code: your if
statement at the very end is not indented, and therefore not part of the for
loop. It is only being executed once, after the loop ends, meaning prime
will be the last value set (where a
is 999
, not a prime). You want to indent the entire if
statement to be in your inner for
loop. You could condense this, though:
for a in xrange(1, 1000):
for divisor in xrange(2, a):
if a % divisor == 0:
break
else:
print a
numberlist.append(a)
Note that this uses the for ... else
clause. Putting else
at the end of a for
loop will cause that else
block to run only if the loop is not broken by break
.
As a further comment, starting the whole loop at 1
will have 1
in the list, but 1
is not a prime.
a/divisor evaluates to an int since both a and divisor are ints, so a/divisor == int(a/divisor) is always true. Try checking the remainder after division... the modulus... I think that in Python, maybe
if a % divisor == 0:
...
This basically says "if the remainder after dividing a by divisor is zero, then".
You never reset prime
to True
.
I think you forgot to reset prime
's value to True
on each iteration.
It may help you when you get further along to know that there are 168 primes less than 1000.
精彩评论