60850

How can I verify that a variable is a number in Python?

Question:

I am writing a code on the subject of engineering which requires the user to input several values which the program will then work with.

At the moment I have the following code:

while True: strainx =input("Please enter a value for strain in the x-direction: ") num_format = re.compile("^[1-9][0-9]*\.?[0-9]*") isnumber = re.match(num_format,strainx) if isnumber: break

In simple terms I am trying to ask the user to enter a value for strainx which is a number. If the user enters anything other than a number then the question will be repeated until they enter a number. However, by using this method the code does not accept decimals and there will be instances where the user must enter a decimal. Is there any way around this?

Answer1:

Just try casting to a float and catching a ValueError if the user enters something that cannot be cast:

while True: strainx = input("Please enter a value for strain in the x-direction: ") try: number = float(strainx) break # if valid entry we break the loop except ValueError: # or else we get here, print message and ask again print("Invalid entry") print(number)

casting to float covers both "1" a "1.123" etc..

If you don't want to accept zero you can check after casting is the number is zero, I presume negative numbers are also invalid so we can check if the number is not <= 0.

while True: strainx = input("Please enter a value for strain in the x-direction: ") try: number = float(strainx) if number <= 0: print("Number must be greater than zero") continue # input was either negative or 0 break # if valid entry we break the loop except ValueError: # or else we get here, print message and ask again print("Invalid entry") print(number)

Answer2:

If you insist of using regex, this pattern appears to work:

"^(\-)?[\d]*(\.[\d]*)?$"

Match optional negative sign, match any number of digits, optional decimal with any number of digits.

Tip: You can use isnumber = bool(re.match(num_format,strainx) or the latter part directly into the if statement.

Answer3:

If you are looking for Integer check then try this -

isinstance( variable_name, int )

If it returns True then the variable is number else it's something else.

But if you want to check if the character value is number or not. eg - a = "2" above script will return False. So try this -

try: number = float(variable_name) print "variable is number" except ValueError: print "Not a number"

Answer4:

If you are using Python 2, instead of using regular expressions, you can use Python's in built type checking mechanisms.

Let's loop while strainx is not a number, then check whether the latest input is a number.

is_number = False while not is_number: strainx =input("Please enter a value for strain in the x-direction: ") is_number = isinstance(strainx, float) or isinstance(strainx, int)

Recommend

  • Datagridview to Clipboard with formatting
  • List comprehensions with float iterator in F#
  • How to get the input from a text box on a webpage form
  • Multiple Dispatch with Generics
  • OpenCV imread with foreign characters
  • I want to bind the click event to the li elements in the xpages type-ahead
  • need to identify dynamic input/textareas when inserting to database
  • How to dynamically generate javascript using ScriptSharp?
  • Cast uint -> double invalid?
  • Windows batch string manipulation in loop
  • web shop (shopping cart) on google app engine
  • javascript add operation returns bad result
  • Sum values in array of hash if they have the same value
  • What does a hyphen at end of a term mean
  • Flex/AS3 very strange simple Number operation issue
  • LNK1104: cannot open file 'kernel32.lib'
  • Can XOR be expressed using SKI combinators?
  • Invert string in Rust
  • How to repeat sections of a SQL query across UNIONs? (DRY in SQL)
  • Less Conflicting Session Manager for Zope 2
  • Where these are stored?
  • XSLT foreach repeating nodes to flat
  • Yii2: Finding file and getting path in a directory tree
  • Clear activity stack before launching another activity
  • How to detect interior vertices in groups of 2d polygons? (E.g. ZIP Codes to determine a territory)
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • calculate gradient output for Theta update rule
  • C++ pointer value changes with static_cast
  • How do I configure context broker accept post requests from my remote sensor?
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • C++ Partial template specialization - design simplification
  • Is there a javascript serializer for JSON.Net?
  • Deserializing XML into class C#
  • Where to put my custom functions in Wordpress?
  • Trying to switch camera back to front but getting exception
  • Buffer size for converting unsigned long to string
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Programmatically clearing map cache
  • Binding checkboxes to object values in AngularJs