I've been working on this script all weekend and am almost done with it accept for one last detail; implementing a "process another number?" prompt after a user input is processed.
The script works like this: First, the user enters a number to test (to find the two prime numbers that make up that number). Next the program finds the numbers, outputs them, then quits.
What I want to do is create a prompt after the number has been processed that asks the user if they want to try another number or quit. I tried doing this but it isnt working rite... As it is now, after the user enters yes to continue the script simply exits instead of asking the user for another number.
Here is that output:
This program finds two prime numbers that add up to any even number you enter.
Enter an even integer larger than 2: 6
Found two prime numbers that sum to 6 !
6 = 3 + 3
Would you like to try another number (yes or no)? y
Could someone please show me what i'm doing wrong and how to get it working rite?
Heres my code:
import math def is_prime(p): if p == 2: return True else: return prime_test(p) def is_even(n): return n % 2 == 0 def prime_test(p): stop = int(math.ceil(math.sqrt(p))) + 1 if p % 2 == 0: return False else: for i in range(3, stop, 2): if p % i == 0: return False return True # is a prime def validated_input(moredata): while moredata == "y" or moredata == "Y": input = raw_input("\nEnter an even integer larger than 2: ") try: n = int(input) except ValueError: print "*** ERROR: %s is not an integer." % input for x in range(2, int(math.ceil(math.sqrt(n))) + 2): if n % x == 0: break if x == int(math.ceil(math.sqrt(n))) + 1: print "*** ERROR: %s is already prime." % input if is_even(n): if n > 2: return n else: print "*** ERROR: %s is not larger than 2." % n else: print "*** ERROR: %s is not even." % n return None def main(): print "This program finds two prime numbers that add up to any even number you enter." moredata = "y" n = validated_input(moredata) if n: for p in xrange(2, int(math.ceil(math.sqrt(n))) + 2): if is_prime(p) and is_prime(n - p): print "="*40,"\nFound two prime numbers that sum to",n,"!" print n, '= %d + %d' % (p, n - p),"\n","="*40 moredata = raw_input("\nWould you like to try another number (yes or no)? ") if __name__ == '__main__': main()