[Tutor] help with user input
Donald Bedsole
drbedsole at gmail.com
Mon Mar 21 23:02:30 CET 2011
Thank you, Marc
On Mon, Mar 21, 2011 at 4:47 PM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Mon, Mar 21, 2011 at 1:12 PM, Donald Bedsole <drbedsole at gmail.com> wrote:
>>
>> 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."
>>
> I think that's because you're trying to do a string comparison, rather than
> a numeric comparison. (if next <= "50":) You need to convert 'next' to an
> int FIRST, then compare to 50, not "50".
>
>>
>> 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?
>>
>
> If you don't want to use an exception, check the entered value first (note:
> I haven't checked my code, so caveat lector) -
>
>> next = raw_input(">")
>> if next.isdigit():
>> if int(next) < 50:
>> print "Nice, you're not greedy, you win!"
>> else:
>> dead("You were too greedy.")
>> else:
>> dead("Man, learn to type a number!")
>
> isdigit() returns True if every character is a digit; False otherwise.
> http://docs.python.org/library/stdtypes.html
>
>
> Using an exception:
>
>> next = raw_input(">")
>> try:
>> if int(next) < 50:
>> print "Nice, you're not greedy, you win!"
>> else:
>> dead("You were too greedy.")
>> except ValueError:
>> dead("Man, learn to type a number!")
>
> Note that I specified ValueError - you want to make your exception handling
> as specific as possible, so that if really unforeseen things go wrong, your
> program doesn't blindly treat them as normal. In other words, if any
> exception other than ValueError were to pop up here, you would want the
> program to terminate and show you a traceback so you could fix it.
>
>
>
It'll take me awhile to digest this. Thanks for your time and your help.
More information about the Tutor
mailing list