[Tutor] help with user input

Donald Bedsole drbedsole at gmail.com
Mon Mar 21 21:12:18 CET 2011


I'm going through a tutorial called "Learn Python the Hard Way" by Zed
Shaw.  At the end of his lessons he has "Extra Credit" sessions, and
I'm stuck on one.

I'm on lesson 35, here is a link to it:

http://blamcast.net/python/ex35.html

The lesson involves creating a very simple text based game.  One of
the functions accepts user input:

def gold_room():
    print "This room is full of gold.  How much do you take?"

    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")


The instruction from the Extra Credit section reads:

The gold_room has a weird way of getting you to type a number. What
are all the bugs in this way of doing it? Can you make it better than
just checking if "1" or "0" are in the number? Look at how int() works
for clues.


I have read the documentation for int() and done some googling, but no
lights have come on. :-)

Here is what I have so far:

def gold_room():
    print "This room is full of gold. How much do you take?"

    next = raw_input("> ")
    if next <= "50":
        how_much = int(next)

    else:
        dead("You were too greedy.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
	exit(0)

    else:
        dead("Man, learn to type a number!")


This works fine as long as the user enters a number.  However, if they
enter anything else, they just get the first :else statement, "You
were too greedy."

My googling found solutions using an exception, but that hasn't been
introduced yet in the tutorial.  How would you solve this without
using an exception?

Thanks for any help,

Don


More information about the Tutor mailing list