[Tutor] Error checking and such in a console "guess my number" game

Alan Gauld alan.gauld at btinternet.com
Tue Jan 8 09:56:13 CET 2008


Hi Brett,

If this is really just your second program then I think you
are being a bit too ambitious. I'd try simplifying it a bit first,
get it to work and then add the extra features - like all of
the error checks etc. As it stands there are a few basic
errors to be fixed.

> #main body
> guessed_number = 0
> stop = "n"
> times_played = 0
> range_for_random = 0
> inter_range = ''
> default = 100

You don't really need to define all the variables up front,
but there's no harm in doing so.

> while 1:

Now that Python supports boolean types its better
to write this as

while True:


>    inter_range = raw_input("\n\n Please specify the range for the
> randon number to reside within: ")
>
>    alphabet = "abcdefghijklmnopqrstuvwxyz"
>    intermediary_number = raw_input("\n\nPlease enter your guess, or
> type stop to end game: ")
>
>    if intermediary_number == "stop":
>        exit()

exit() is part of the sys module which you haven't imported yet...

>    elif 1:

This is always true so you don't need it.

>        for char in alphabet:
>            if char in inter_range:

inter_range is supposed to be a number (or the
character representation of a number since we
haven't converted it yet) but here we check
every letter in the alphabet to see if its in that
number, which is highly unlikely to happen
unless the user typed "eleven" or similar

So I'm not sure what you think this loop will do.

>                range_for_random = default
>                continue
>            else:
>                if inter_range == '':
>                    range_for_random = default
>                else:
>                    range_for_random = int(inter_range)

The empty string check is reasonable but the
else will be repeated for most letters of the
alphabet so that at the end of the loop you will
wind up with an int version of inter_loop, which
is what you want, but you got there byy a very
complicated route!

>    while 1:
>        if times_played > 0:

times_played is set to zero at the top and nothing changes
it up to here so this will never be true.

>            stop = raw_input("\n\nTo end the game, type in stop, Or 
> to
> change the range, type change. Otherwise just press Enter:")
>            if stop.lower() == "change": break

Since there is nothing beyond the outer while loop
this will stop the program not change the values.

>            elif stop.lower() == "stop": exit()
>        print "\n\nTime to start Guessing My Number!"
>        random_number = random.randrange(range_for_random) + 1
>
>        while 1:
>            alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet hasn't changed so you don;t need to define it again.

>            intermediary_number = raw_input("\n\nPlease enter your
> guess, or type stop to end game: ")
>
>            if intermediary_number == "stop":
>                exit()
>            elif 1:
>                for char in alphabet:
>                    if char in intermediary_number:
>                        guessed_number = 0
>                        continue
>                    else:
>                        if intermediary_number == '':
>                            guessed_number = 0
>                        else:
>                            guessed_number = int(intermediary_number)

Again, this is a very complicated way of getting where you
want to go most of the time. Rather than checking every letter
in alphabet it would be better to apply some rules to the
intermediary number itself.

try:
     guessed_number = int(intermediary_number)
except: guessed_number = 0     # for any error at all.


>            if guessed_number > random_number:
>                print "\nYour guess was too high!"
>            elif guessed_number < random_number:
>                print "\nYour guess was too low!"
>            elif guessed_number == random_number:
>                print "\nYes, you got the right answer! The answer 
> was:
> " + str(random_number)

You don;t need to convert back to a str, just separate with a comma:

 print "\nYes, you got the right answer! The answer was: 
",random_number

>                times_played += 1

You only update times_played if they get it right. Are you sure
thats what you want? It is if times played means the number
of differnt numbers guessed, but not if its the number of
guesses per number...

>                print "You have now played %s time(s)." % 
> (times_played)
>                break

> Now I was wondering first off, is there a better way about doing the
> error checking?

Yes, see the comments above.

> I already tried try-except blocks, but as I'm new to
> python (this is my second program after "Hello World") I don't know 
> how
> to only catch certain exceptions (in this case a ValueError).

In fact I suspect you don't care about the specific type of error
since you always set a default value. But if you do want to
catch only one error type simply list them in the Except clause:

try:
    # your code here
except ValueEerror:
    # handle the error

> try-except without limiting seems to disable Ctrl+C breaking in the
> console, I found.

Thats because Ctrl-C generates an exception so yes it will catch
that too. If you limit the try/except to just the convertion operation
it shouldn't be a problem since the try/except will be so short lived.

> The next thing is my real problem:
>
> if times_played > 0:
>            stop = raw_input("\n\nTo end the game, type in stop, Or 
> to
> change the range, type change. Otherwise just press Enter:")
>            if stop.lower() == "change": break
>            elif stop.lower() == "stop": exit()
>
> What I want the break statement to do here is exit the while loop 
> isn't
> currently in, but it just seems to break the current if decision, 
> making
> it rather redundant. A little help with this in particular would be 
> much
> appreciated :)

It shouldn't. It should exit the loop. Try it with a simpler example
to check how it works.

> And just so you know, I'm teaching myself python, for fun and for an
> upcoming job, and this is just fun for me.

Learning for fun is good :-)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list