May-25-2018, 01:08 AM
Pages: 1 2
May-25-2018, 01:13 AM
var = '12313210' if var.isnumeric() and '.' not in var: print("The value is integer")
May-25-2018, 01:18 AM
var = 5
print(var.isnumeric())
returns an error, i was expecting TRUE
print(var.isnumeric())
returns an error, i was expecting TRUE
May-25-2018, 01:35 AM
.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")
May-25-2018, 06:23 AM
the common way is
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
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
May-25-2018, 07:05 AM
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.
May-25-2018, 07:07 AM
My explanation was mainly for benefit of the OP :-)
May-25-2018, 07:13 AM
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:16 AM
(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 :-)May-25-2018, 07:20 AM
I didn't write something for someone for a long time. Honestly, I don't remember what I did the last time. 

Pages: 1 2