username = input("What do you want your username to be? ")
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return number == 2
divisor = 3
while divisor * divisor <= number:
if number % divisor == 0:
return False
divisor += 2
return True
def prime_finder():
try:
number = int(input("Choose a number: "))
except ValueError:
print("ERR: not a valid number")
return
if is_prime(number):
print(number, "is prime")
else:
print(number, "is not prime")
def end():
print("Goodbye,", username)
while True:
print("prime-finder.py v1.0")
print("1. prime finder")
print("2. quit")
try:
answer = int(input("Make your choice: "))
except ValueError:
print("ERR: invalid input")
continue
if answer == 1:
prime_finder()
elif answer == 2:
end()
break
else:
print("ERR: invalid input")
This is good for a beginner, but be warned that it isn’t performant. Besides, “prime finder” is a misleading name when this program only checks if the input is prime.
I would re-write it as:
while True:
print("prime-finder.py v1.0")
print("1. prime finder")
print("2. quit")
try:
answer = int(input("Make your choice: "))
if answer == 1:
prime_finder()
break
elif answer == 2:
end()
break
else:
print("ERR: invalid input")
except ValueError:
print("ERR: invalid input")
continue
You should move the first print outside the loop.
How would you make it performant?
What I meant was that OP should not expect this algorithm to be competitive against advanced algorithms such as ECPP for larger inputs, but the program in its current state is fair. There is also an optimization that can be made without introducing significant complexity; since primes larger than 3 are all of the form 6k + 1 or 6k - 1 for some positive integer k, after checking 2 and 3, the increments at each iteration can follow a cycle beginning from 1, namely (4, 2, 4, 2, …). This can be extended to a bigger basis such as (2, 3, 5) and the cycle starting from 1 would be (6, 4, 2, 4, 2, 4, 6, 2, …).