Last active
December 29, 2015 20:09
-
-
Save macloo/7721695 to your computer and use it in GitHub Desktop.
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, a good example (for beginners) of use of a while loop | |
# journalism students often ask how one would use modulo - this shows them one case | |
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." | |
n = raw_input("Enter a whole number: ") | |
def testfor100(a): | |
a = int(a) | |
# below is a while loop that quits as soon as | |
# you enter a number less than 100 | |
while a >= 100: | |
print "Please enter a number that is less than 100." | |
a = raw_input("> ") | |
a = int(a) | |
return a | |
# this runs the function above | |
# the n in parens below feeds the value of n into the function where it has (a) | |
n = testfor100(n) | |
for num in range(2, n): | |
# below, % is the modulus sign | |
# see http://learnpythonthehardway.org/book/ex3.html | |
remainder = n % num | |
# 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, num, remainder) | |
if remainder == 0: | |
print "Sorry, %d is not a prime number." % n | |
break | |
if num == 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