[sf-lug] ThinkPython: coding problem
a_kleider at yahoo.com
Sat Oct 11 07:13:51 PDT 2008
--- On Sat, 10/11/08, Asheesh Laroia <asheesh at asheesh.org> wrote:
> From: Asheesh Laroia <asheesh at asheesh.org>
> Subject: Re: [sf-lug] ThinkPython: coding problem
> To: "Linux userGroup" <sf-lug at linuxmafia.com>
> Date: Saturday, October 11, 2008, 1:40 AM
> On Fri, 10 Oct 2008, Alex Kleider wrote:
> > # ThinkPython: question-
> > As part of our ThinkPython class exercises I want to
> > check user input.
> > i.e. the user is asked to enter a number and I want
> the routine
> > to check that it is indeed a number that is entered.
> > It seems that everything "collected" by
> raw_input is considered
> > a string, even if only digits are included.
> You can always convert a string to an int by doing:
> >>> inputted_thing = '3'
> >>> type(inputted_thing)
> <type 'str'>
> >>> as_number = int(inputted_thing)
> >>> type(as_number)
> <type 'int'>
> Note that this does no error checking. In Python you would
> typically do
> that with exceptions, and I don't think we've
> gotten there yet.
> -- Asheesh.
When I run the following program:
response=raw_input('Please enter a number: ')
If the input is a letter rather than a digit, it crashes:
alex at ibmtp:~/Python/Ex$ python test_al
Please enter a number: p
Traceback (most recent call last):
File "test_al", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'p'
alex at ibmtp:~/Python/Ex$
It seems there is error checking going on.
More information about the sf-lug