I was trying to write a program that would display the prime numbers between 2 and 200.
This is the program that i wrote.
liste = [ ]
liste.append(2)
liste = [2]
for primeCandidate in range (2,10):
isPrime = True
for divisor in range (2,primeCandidate):
if primeCandidate % divisor == 0:
isPrime = False
break
if isPrime:
liste.append(primeCandidate)
print(liste)
But I always get a wrong output. And I couldn't find my mistakes. Can you help me finding my mistakes?
Two things leap out:
(1) You don't need to set liste to [2] at the start; your primeCandidate loop includes 2, so you'll get 2 twice if you do.
(2) Your "if isPrime" is one level too deep. You can only trust isPrime after you've checked the candidate divisors. (Well, you're actually checking more than you need, but that's only an efficiency issue, not a bug.) To be specific:
liste = []
for primeCandidate in range (2,100):
isPrime = True
for divisor in range (2,primeCandidate):
if primeCandidate % divisor == 0:
isPrime = False
break
if isPrime:
liste.append(primeCandidate)
print(liste)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With