Im trying to create a menu-driven program that will calculate and display all the prime numbers between 2 and a user-entered limit. The first option the user could pick would be "Create a list of primes from 2 to n using the Sieve of Eratosthenes algorithm". The second option would be "Display the prime numbers", and the third would be to quit. My code currently looks like:
def main():
choice = displayMenu()
while choice!= '3':
if choice == '1':
sieve()
elif choice == '2':
prime
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' and myChoice != '3':
print("""Please choose
1. Create a list of primes from 2 to n using
the Sieve of Eratosthenes algorithm
2. Display the prime numbers
3. Quit
""")
myChoice = input("Enter option--->")
if myChoice != '1' and myChoice != '2' and myChoice != '3':
print("Invalid option. Please select again.")
return myChoice
def sieve():
liste = [ ]
n = int(input("What number should I go up to?"))
choice = input("--->")
for primeCandidate in range (2,n):
isPrime = True
for divisor in range (2, primeCandidate):
if primeCandidate % divisor == 0:
isPrime = False
break
if isPrime:
liste.append(primeCandidate)
print(liste)
main()
What I am finding is that when I print the primes from 2 to 13 for example is that it prints it as
[3]
[3, 5]
[3, 5, 5]
[3, 5, 5, 5]
[3, 5, 5, 5, 7]
[3, 5, 5, 5, 7, 7]
[3, 5, 5, 5, 7, 7, 7]
[3, 5, 5, 5, 7, 7, 7, 7]
[3, 5, 5, 5, 7, 7, 7, 7, 7]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11, 11, 11, 11]
[3, 5, 5, 5, 7, 7, 7, 7, 7, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11]
Is there a way to correct that and only print each prime number once?