[Tutor] Help with "Guess the number" script

Danny Yoo dyoo at hashcollision.org
Tue Mar 4 11:08:11 CET 2014


Once a function gets beyond about six or seven lines long, it's a bit
hard to read, and harder to get the indentation right.  You're having
difficulty with the indentation, but that's often a sign that the
function is too big to read comfortably.

Can you break the function down into a few pieces?

I see there's some duplicated blocks, such as:

#########################
print "You are cold!"
print
print "Please play again!”
#########################
You can define a function to do these three prints:

#########################
def print_cold():
    print "You are cold!"
    print
    print "Please play again!”
#########################

Once you have this somewhere, you can use print_cold() whenever you
want to do those three prints statements.  Try it!


Try to do the same for your other messages.  You'll find that it
should help make print_hints() more concise.  Hopefully it'll be short
enough that you can see where you're misindenting.


Making it shorter should help make it easier to see that the code
testing for "coldness" is not quite consistent from one place to
another.  In one, the code uses a threshold of ten, but in another
place, a threshold of five.  Is that difference intentional?


If not, then you might even try something like:

#########################
def maybe_print_cold():
    if guess < (secret - 10) or guess > (secret - 10):
        print "You are cold!"
        print
        print "Please play again!”
#########################

and use this function in the two places where you're checking for coldness.


Point is: use functions.  They're there to help.


More information about the Tutor mailing list