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
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:
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.
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)