Newbie Help
Peter Hansen
peter at engcorp.com
Mon Jun 21 02:12:17 EDT 2004
cronje_med wrote:
> Ok, so I'm a bit new at this, so please don't make fun of me too much.
You won't find folks doing that around here... this is a nice
newbie-friendly group, for the most part (even if some misinterpret
my attempts at humour :-).
> I was trying to make a math function that wouldn't pull a NameError
> if I didn't enter a number or variable containing a number. Here's
> what I have:
>
> def math(num):
> if num.isdigit() == 1:
> print "Is a number!"
> return num
> else:
> print "Is not a number!"
> return num
>
>
>>>>math(5+5)
> AttributeError: 'int' object has no attribute 'isdigit'
>
>>>>math("5+5")
> Is not a number!
> '5+5'
>
>>>>math("5+x")
> Is not a number!
> '5+x'
def testNum(num):
try:
num + 1
print 'Is a number!'
return num
except TypeError:
print 'Is not a number!'
return num
In Python, the most elegant way to check something like that is
to try to use it _as_ such a thing. If that fails, catch the
exception that's raised and carry on... The above tries to
add one to the number, which should work for anything that
acts like a number, but fail for most other things...
-Peter
More information about the Python-list
mailing list