HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Number guessing game for beginners

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberbeginnersgameforguessing

Problem

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 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? ")
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("\nGue

Solution

There is a serious problem at:

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


This function mixes user interaction (printing and sleeping) and logic (returning a random number). This is basic separation of intents, and should be taught to beginners from the start.

The same can be seen at:

def hi_low_done(delta):
    if delta  0:
        print "Guess higher."
        return False
    else:
        print "You got it!"
        return True


This function should only return a message, not return a message and print.

About to_int

def to_int(x):
    try:
        x = int(x)
        return x
    except ValueError:
        print "That is not a whole number."
        return False


While it is possible to return different types from a function in Python, it is a symptom of bad design. I reccomend writing a is_int method to return True or False if the argument is an int and then converting to int with int.

Further refactoring

Asking a user for yes or no is a common task and should be its own function, also using startswith is more flexible and allows 'yeah' and 'yup' for example.

Also you should write a function to generate the message. You then print it and break if guess and real number are equal.

Use Python 3

Python 3 is continually improved while Python 2 is deprecated, it makes more sense to teach 3 than 2 (The two are similar just use parens around print).

Avoid needless comments

Comments should tell why not what, if you write

# imports


You just add noise as it is obvious that the following lines are imports.

Define a main function and call it

It is a good habit to get into and allows the importing of scripts.

Like:

def number_guessing_game(minimum, maximum):
     # All your currently top level code

if __name__ == "__main__":
    number_guessing_game()

Code Snippets

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 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
def to_int(x):
    try:
        x = int(x)
        return x
    except ValueError:
        print "That is not a whole number."
        return False
def number_guessing_game(minimum, maximum):
     # All your currently top level code

if __name__ == "__main__":
    number_guessing_game()

Context

StackExchange Code Review Q#97463, answer score: 8

Revisions (0)

No revisions yet.