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 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 alwaysTrue, because division in Python is integral (you will always get an integer result). Usea % divisor == 0instead.Another problem is that
prime = Trueis outside the loop, meaning that as soon as one value is declared not prime, no more values can be prime! (primewill never get set back toTrueanywhere.)A third issue, more of style, is that it is preferred to use a
for ... inloop in python, egEdit: Regarding your modified code: your
ifstatement at the very end is not indented, and therefore not part of theforloop. It is only being executed once, after the loop ends, meaningprimewill be the last value set (whereais999, not a prime). You want to indent the entireifstatement to be in your innerforloop. You could condense this, though:Note that this uses the
for ... elseclause. Puttingelseat the end of aforloop will cause thatelseblock to run only if the loop is not broken bybreak.As a further comment, starting the whole loop at
1will have1in the list, but1is not a prime.