import random import math def isprime(num): """Returns True if the input is a prime number, False otherwise""" for i in range(2, int(math.sqrt(num)+1)): if num % i == 0: return False return True def firstprimes(num): """Prints out the first num primes""" count = 0 # the number of primes we've printed out current = 2 # the current number we're checking while count < num: if isprime(current): print current count += 1 # same as count = count + 1 current += 1 # same as current = current + 1 def number_guessing_game(): """Play a number guessing game where the user tries to guess a number between 1 and MAX_GUESS and is given hints for lower and higher""" MAX_GUESS = 20 number = random.randint(1, MAX_GUESS) finished = False while not finished: guess = int(raw_input("Guess a number between 1 and " + \ str(MAX_GUESS) + ": ")) if guess == number: print "Good job!" finished = True elif guess < number: print "A bit higher" else: print "A bit lower" # here's an alternate way of writing it that doesn't use a # bool variable. Either way is fine. def number_guessing_game2(): """Play a number guessing game where the user tries to guess a number between 1 and 20 and is given hints for lower and higher""" number = random.randint(1, 20) guess = 0 # start it out as some number that can't be right while guess != number: guess = int(raw_input("Guess a number: ")) if guess < number: print "A bit higher" else: print "A bit lower" # when we exit the loop, we know the user's gotten it right print "Good job!"