I am teaching a python class to some high school seniors. I was thinking of doing an "oracle" game where the computer would come up with a number, and the player would guess it. These are brand new coders, and I'll teach them what they need to know to get there, but is this a good first project? I have my code here as my implementation of this game. I want to make sure that I don't teach them anything bad or give them bad habits.
My software requirements are:
- Must generate a random (or psuedo-random) number
- Must import a library
- Must use a loop
- Must take user input
- Must tell the user to guess higher or lower
# imports import random import time import sys import os # set global variables MIN_NUMBER = 1 MAX_NUMBER = 10 # important functions def get_random(min, max): print "Coming up with a number." time.sleep(2) random_number = random.randint(min, max) print "Got it!" return random_number def to_int(x): try: x = int(x) return x except ValueError: print "That is not a whole number." return False def how_close(guess, right_answer): return right_answer - guess def hi_low_done(delta): if delta < 0: print "Guess lower." return False elif delta > 0: print "Guess higher." return False else: print "You got it!" return True # main Program #clear screen os.system('cls') # on windows print "Welcome. I am the Oracle." print "I will think of a number between %s and %s. Guess it and you will win!" % (MIN_NUMBER, MAX_NUMBER) while True: user_answer = raw_input("Ready? <y/n> ") if user_answer.lower() == 'y' or user_answer.lower() == 'yes': print "Great! Let's go." break; elif user_answer.lower() == 'n' or user_answer.lower() == 'no': print "Okay. Consult the Oracle when you are ready." sys.exit() oracles_number = get_random(MIN_NUMBER, MAX_NUMBER) number_of_guesses = 0 while True: number_of_guesses = number_of_guesses + 1 user_answer = raw_input("\nGuess> ") user_answer = to_int(user_answer) # if user answer is outside min max... else... if user_answer: delta = how_close(user_answer, oracles_number) done = hi_low_done(delta) if done: break; print "It took you %s guesses to guess my number." % (number_of_guesses)
I guess my concerns with my code are:
- Is this simple enough? It isn't the first thing they will code, but the first project they will do. (maybe group project?)
- Did I make any blatant errors or "In python, you should do this instead" errors? Python isn't my first language so I'm not sure.
I have created a gist file with my most up-to-date version of this.