[Tutor] Convert String to Int

Ian Egland echolynx at gmail.com
Mon Jan 19 02:43:54 CET 2009


Actually, nobody told me how to catch it before it occurs, though this
"after error" stuff is new to me.

Could you send an example of how to catch it beforehand? Just for the
record?

Thanks.
Ian

On Sun, Jan 18, 2009 at 8:35 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:

> On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland <echolynx at gmail.com> wrote:
>
>> I know that, should you want to get an int from the user, you use
>> int(input("Question!")). However, what if the user wasn't that savvy and
>> didn't realize he/she HAD to enter a number? Program crash. Is there a way
>> that I can get the input as a string, check and see if it's convertible to
>> an integer, convert it if it is and ask them to try again if it's not?
>>
>>
> You have two options: to test the input ahead of time, or to catch the
> crash.  Believe it or not, number two is usually the preferred method
> (there's a programming axiom "It's better to ask forgiveness than
> permission")  In Python, you put the operations that have a potential for
> disaster inside a try/except block, like so:
>
> try:
>>     int(input("Question!"))
>>     do whatever...
>> except:
>>     ask again...
>> do the next thing
>>
>
> When Python "crashes", an Exception is generated, which carries all sorts
> of useful information about just what went wrong.  It's good form to try to
> guess what the error might be before catching it (how many times have you
> been frustrated by some commercial program that says "Out of memory" {or
> some other catch-all} any time ANYTHING bad happens?  It's because the
> programmer assumed that the only errors that would ever come up would be
> memory-related.  Don't be that guy.)  For example, do a test run like so:
>
>> >>> int('hello')
>> Traceback (most recent call last):
>>   File "<input>", line 1, in <module>
>> ValueError: invalid literal for int() with base 10: 'hello'
>>
>
> Now you know that invalid input would result in a ValueError, so change my
> above code to:
>
>> try:
>>     int(input("Question!"))
>>     do whatever...
>> except ValueError:
>>     ask again...
>> do the next thing
>>
>
> Someone else will no doubt already have posted how to test your input ahead
> of time - I thought I'd chime in with the other method...
>
>
> --
> www.fsrtechnologies.com
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090118/890ff4c2/attachment.htm>


More information about the Tutor mailing list