I’ve created a prime number generator and wanted the user to specify the number of prime numbers generated. I was wondering how I could change “1000” to a raw_input without the program throwing errors back at me as it has been doing. Also how do I save this list generated to a .txt file? Thanks in advance
Code:
no_of_primes = 1
candidate = 2
start = 2
list_of_primes = []
while no_of_primes <= 5000:
result = candidate % start
if result > 0:
start +=1
elif result == 0:
if start == candidate:
list_of_primes.append(candidate)
candidate +=1
no_of_primes +=1
start =2
else:
candidate +=1
start = 2
print list_of_primes
First, replace the
5000with a variable (like, say,primes_to_generate). Then before thewhileloop, set that variable by callinginton the result ofraw_input. Theintwill convert it from a string to a number, fixing your error:You can also use a
tryblock to catch errors for if someone, say, types in “ninety” rather than “90”: