[sf-lug] ThinkPython: coding problem
jim at jimcortez.com
Sat Oct 11 10:44:13 PDT 2008
There are 3 simple ways to tackle this (at a beginner's level).
You can also use the input() function to read in a number. The downside,
however, is that it will result in an error if the user enters in a string.
To handle that error, you can use the try, except method to recover.
Sometimes, however, python will throw a different error than you expected.
Read the message at
http://docs.python.org/library/functions.html?highlight=input#input for more
>>> a = input()
>>> a = input()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'blah' is not defined
You may also think of using isinstance for type checking. This takes in an
object, and a type and then looks to see if the 2 types match up.
>>> isinstance(8, int)
And last, if you decide to use raw_input(), then you can also use .isdigit().
Take a look at
for isdigit and a couple other handy string functions.
I hope that helps!
On Friday 10 October 2008 9:42:27 pm 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.
> def int_check(n):
> if type(n)==int:
> return True # as used below, NEVER returns True.
> return False
> response=raw_input('enter a number: ')
> if int_check(response):
> pass #procede with what needs to be done
> pass #take corrective action
> Can anyone suggest how I can accomplish this?
> I'm familiar with Pascal and its strong typing which would prevent such a
> problem from occurring as a runtime problem (vs a syntactic error.)
> sf-lug mailing list
> sf-lug at linuxmafia.com
More information about the sf-lug