Python Forum

Full Version: test if variable is Numeric?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
hi, in Visual Basic i can use IsNumeric() function, returns T/F. How do I test if a variable is an integer in python... using standard library

tahnks
var = '12313210'
if var.isnumeric() and '.' not in var:
    print("The value is integer")
var = 5
print(var.isnumeric())

returns an error, i was expecting TRUE
.isnumeric is string method.So, var should be a string.
If you already know that the variable is of numeric type, you can test it using type-function:

if type(var) == int:
    print("var is integer")
the common way is
var = 5
print(isinstance(var, int))
note that you can supply multiple types as second argument

var = 5
var2 = 1.2
var3 = 'some text'
print(isinstance(var, (int, float)))
print(isinstance(var2, (int, float)))
print(isinstance(var3, (int, float)))
read https://docs.quantifiedcode.com/python-a...tance.html or https://stereochro.me/ideas/type-vs-isinstance why isinstance() is preferable than type()
At the end of the link there is also link to other resources why checking for type is against python principles/design patterns. You probably have heard that it's easier to ask for forgiveness than permission and "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck" (https://docs.python.org/3.6/glossary.html , check EAFP and duck-typing) https://en.wikipedia.org/wiki/Duck_typing
I ask for forgiveness...! In fact, I never use type for type checking in my code, and already knew why it isn't good; In any case, answers should be not only correct, but also clever.
My explanation was mainly for benefit of the OP :-)
If I code for someone else I check the type of the variables or the cli arguments. But if I am doing it for myself... well I don't need it. I know what my script demands.
(May-25-2018, 07:13 AM)wavic Wrote: [ -> ]If I code for someone else I check the type of the variables or the cli arguments.
in this case you should catch the exceptions (in case of unexpected input), not check type... The type of the cli input will always be str anyways :-)
I didn't write something for someone for a long time. Honestly, I don't remember what I did the last time. Big Grin
Pages: 1 2