I know this has been asked before, but I'm trying to learn Python and I don't want the answer handed to me in the form of completed code. I'm hoping someone can just point me in the right direction.
I know how to do loops and functions and stuff, but I don't know how I should set up a check to determine if a number is prime or not. This might actually be a simple math question really.
What math process do I use to find out if a number is a prime?
Here's how it could be broken down:
num_to_test-1, we will try and figure out if
num_to_testis not a prime.
Now, how to do this pythonically?
With Python 3, all you have to do to request an integer input is a line like this:
num_to_test = int(input('What\'s your number?'))
Of course, you want to be sure that the user enters a number, that's why you'll surround this by a
except block and a
while True loop, asking again and again until the answer is valid.
while True: try: # request input if satisfies_your_conditions(num): break else: # explain why not good except ValueError: # print error message
Looping over the integers
First thing to know, you don't need to go further than the square root of
sr = int(math.sqrt(num_to_test))+1
And you'll do the test
for d in range(2, sr). Since we don't have a list of previously verified primes, we'll have to do it for all integers. To check whether
num_to_test, use the modulo operation:
if num_to_test % d == 0: # d does divide num_to_test else: # d does not divide num_to_test
One cool feature is the
for ... : # do your tests, with possibility of breaking the loop else: # this part of the code will only be reached if the loop did not break
With this, you'll be able to set a boolean to
False and then
You could use the ternary operator for this:
print('some string' if is_prime else 'another string')
This is only a possibility of implementation among others.
import math def main(): while True: try: num_to_test = int(input('What\'s your number? ')) if num_to_test == int(num_to_test) and num_to_test > 2: break else: print('Must be an integer larger than 1. Try again.') except (NameError, ValueError): print('Not a number. Try again.') sr = int(math.sqrt(num_to_test))+1 for d in range(2, sr): if num_to_test % d == 0: is_prime = False break else: is_prime = True print('%d is a prime number'%num_to_test if is_prime else '%d is not prime'%num_to_test) if __name__ == '__main__': main()