Created
December 17, 2013 16:15
-
-
Save macloo/8007581 to your computer and use it in GitHub Desktop.
Simple example of using modulo (modulus) to test for a prime number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# testing for a prime number - use of modulo (modulus) | |
# also, good example of a for loop | |
n = 0 | |
print "\nWe will test a number to find out whether it is prime." | |
print "Try it with 25. Then try it with 7 or 13." | |
print "Then try it with any number you like (but not too large a number!)." | |
n = raw_input("Enter a number: ") | |
n = int(n) | |
for counter in range(2, n): | |
# below, % is the modulus sign | |
# see http://learnpythonthehardway.org/book/ex3.html | |
remainder = n % counter | |
# below, % is used with d to represent a variable | |
# called formatters, or format strings: %s %d %r | |
# see http://learnpythonthehardway.org/book/ex5.html | |
print "%d / %d leaves a remainder of %d" % (n, counter, remainder) | |
if remainder == 0: | |
print "Sorry, %d is not a prime number." % n | |
break | |
if counter == n - 1: | |
print "\nHooray! %d is a prime number.\n" % n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Questions for students: