[Tutor] Help with Guess the number script

Peter Otten __peter__ at web.de
Fri Mar 7 10:32:15 CET 2014


Scott W Dunning wrote:

> I am trying to write a script for class for a game called guess the
> number.  I’m almost done but, I’m having a hard time getting the hints to
> print correctly.  I’ve tried ‘if’’ ‘elif’ nested, it seems like
> everything….I’m posting my code for the hints below, any help is greatly
> appreciated!
> 
> def print_hints(secret, guess):
>     if guess < 1 or guess > 101:
>         print
>         print "Out of range!"
>         print
>     if guess < secret:
>         print
>         print "Too low!"
>     elif guess < (secret - 10) or guess > (secret - 10):
>         print "You are cold!"
>         print
>         print "Please play again!"
>     elif guess < (secret - 5) or guess > (secret - 5):
>         print "You are warmer!"
>         print
>     else:
>         print "You're on fire!!"
> 
>     if guess > secret:
>         print
>         print "Too high!"
>         print
>     elif guess < (secret - 10) or guess > (secret - 10):
>         print "You are cold!"
>         print
>     elif guess < (secret - 5)or guess > (secret - 5):
>         print "You are warmer!"
>         print
>         print "Please play again!"
>     else:
>         print "You're on fire!!"

You are trying too much at once. Start with a simple

def get_high_low_hints(secret, guess):
    # buggy; I trust that you can fix it yourself.
    if guess < secret:
        return "too high"
    elif guess > secret:
        return "too low"
    else:
        assert secret == guess
        return "correct"

You can then write simple tests like

assert get_high_low_hints(secret=99, guess=99) == "correct"
assert get_high_low_hints(secret=50, guess=51) == "too high"
assert get_high_low_hints(secret=7, guess=6) == "too low"

(which will fail btw, I added a bug to demonstrate the power of this 
approach) or have a look at the unittest module if you are ambitious. Once 
you have fixed the bugs in get_high_low_hints() you can take the next step

def get_close_far_hints(secret, guess):
    ... # your code; have a look at the abs() function

assert get_close_far_hints(50, 0) == "cold"
assert get_close_far_hints(50, 90) == "cold"

assert get_close_far_hints(50, 59) == "warm"
assert get_close_far_hints(50, 41) == "warm"

... # similar tests for "hot"/"on fire"

In short: break you problem in small sub-problems that you can easily test. 
It may look like it is more work at first, but you are more likely to reach 
a robust working result soon.

Note that my functions do not print anything. This is be because functions 
that don't print are much easier to test:

assert function_that_returns_something() == expected_result

versus

start_capturing_stdout()
function_that_prints_something()
stop_capturing_stdout()
assert get_captured_stdout() == expected_result




More information about the Tutor mailing list