Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

Check if a value is any number in Python

I want to ask if there is a method to check if a value is any number? Is there maybe a "master class" for numbers. I do not want to check every case (int, float, complex). If there is not it is no problem.

In my specific code I now just check every case and than also if it is NaN but that is really annoying.

I have a similar question to data structures: Is there a method that returns whether a value is any of list, tuple, dict or set? Right now I am also checking them every time. So basically my code looks like this:

try:
  value
    if value==None:         #none
      raise Exception("Your value is none")
    elif isinstance(value,str):
      if not value.isnumeric():   #real String
         return value
      else:               #number String
        return (float(value))
    elif isinstance(value,float):
       if math.isnan(value): #nan
         raise Exception("Your number is NaN")
       elif abs(value)>abs(int(value)): #real float
         pass #to-do deal with "real" floats 
       else: #integer
         return int(value)
    elif isinstance(value,int):     #int
      if math.isnan(value): #nan
        raise Exception("Your number is NaN")
      else:
        return value
    elif isinstance(value,tuple):
      pass #to-do recursion
    elif isinstance(value,list):
      pass #to-do recursion
    elif isinstance(value,dict):
      pass #to-do recursion
    elif isinstance(value,set):
      return ("This tool does not support sets yet")
    except NameError: #undefined
        raise Exception("Your value is undefined")

But I feel like it could be much better if there was a method isnumeric() for all values not just strings, like in php.

Regarding my research, I could only find the String isnumeric() method or obviously the type() and isinstance() method.

Please help me but do not tell me there is no better solution.

question from:https://stackoverflow.com/questions/65853315/check-if-a-value-is-any-number-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're willing to do add an import, this works:

import numbers

variable = 5
print(isinstance(variable, numbers.Number))

For the second question, do

x = {}
print(type(x) in [list, dict, tuple, set])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...