[sf-lug] ThinkPython: coding problem

Jim Cortez 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 
information.

Example:
=======
$ python
>>> a = input()
8
>>> a
8
>>> a = input()
blah
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. 
http://docs.python.org/library/functions.html?highlight=isinstance#isinstance

Example:
=======
>>> isinstance(8, int)
True
=======

And last, if you decide to use raw_input(), then you can also use .isdigit(). 
Take a look at 
http://docs.python.org/library/stdtypes.html?highlight=isdigit#str.isalnum 
for isdigit and a couple other handy string functions.

Example:
=======
>>> "8".isdigit()
True
>>> "87654321".isdigit()
True
=======

I hope that helps!
Jim

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.
>   else:
>     return False
>
> response=raw_input('enter a number: ')
> if int_check(response):
>   pass #procede with what needs to be done
> else:
>   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.)
>
> ak
> ~
>
>
>
>
> _______________________________________________
> sf-lug mailing list
> sf-lug at linuxmafia.com
> http://linuxmafia.com/mailman/listinfo/sf-lug





More information about the sf-lug mailing list