[Tutor] Please critique my guessing game program.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Jul 15 04:25:55 CEST 2004

Hi Matt,

Ok, let's take a look:

> import random
> # Function to create a random number between 1 and 100.
> def Random100():
> 	 return random.randint(1,100)

Small note: it looks like you're using tab characters for your
indentation; you may want to switch to 4 spaces, as that seems to be more
prevalent these days.

You can embed that comment about Random100 right in the definition of the
program, as a "documentation string."

For example:

def sayHello():
    """Function that says 'hello!'"""
    print "hello!"

If there's a literal string in the first line of a function definition,
Python will grab it and use it as documentation for the function.

What's nice is that folks can later on ask Python for that documentation
string through the 'help()' builtin:

>>> help(sayHello)
Help on function sayHello in module __main__:

    Function that says 'hello!'

> # Game loop.
> def Game(guess):
> 	guesses = 1
> 	while guess != number:
> 		if guess > number:
> 			guess = input("Too high, try again. ")
> 		else:
> 			guess = input("Too low, try again. ")
> 		guesses = guesses + 1
> 	print "Well done, you got it in",guesses,"goes."

Looks ok here.  As Andrei mentions, input() is a little unsafe, but I
think it's fine here as a quick way to check numbers into the system.

Just as an aside: It might make a good project to write a nice, polished
value-inputting routine.  The C language provides a scanf() function that
makes it pretty easy to read in numbers and words without having to worry
much about whitespace.  Wouldn't it be nice to have the same facility in
Python?  It might look something like:

"""scan.py: provides a nice way to scan integers and words from

## module level global keeps a store of elements ready to be scanned out.
_BUFFER = []

def get_int(prompt):
    """Returns an integer from standard input."""
    while not _BUFFER: _fill_buffer(prompt)
    return int(_BUFFER.pop())

def get_word(prompt):
    """Returns a word from standard input."""
    while not _BUFFER: _fill_buffer(prompt)
    return _BUFFER.pop()

def _fill_buffer(prompt):
    line = raw_input(prompt)
    elements = line.split()

and we can work with it like this:

>>> import scan
>>> scan.get_int("more input please: ")
more input please: 43 44 45
>>> scan.get_int("more input please: ")
>>> scan.get_int("more input please: ")

This is really rough and dirty though, of course... *grin* But would
something like this be useful?

More information about the Tutor mailing list