I am writing a Mathematica command that prompts the user to enter a number.
The "script" stores the user input and then performs a calculation. I want to make sure that the user input is a number, and not a string.
I am looking for a concise check for this constraint.
This is what I came up with:
age = InputString["What is your age?"];
If[NumberQ[ToExpression[age]],
Print["You are ", age, " years old."],
Print["Please enter a number for your age."]
For example, what if the user enters 'seven teen' (so that age = "seven teen"
)? Same question may arise if I want the input to be a positive number, and not a negative number (user input is '-9').
Is there a faster way to make this check, other than an If
conditional?
I came over this tutorial - Putting Constraints on Patterns, and saw these two lines:
pattern/;condition
and
pattern?test
I am asking you for help on how to implement them in the above context.
I am familiar with the built-in testing functions such as NumberQ
, NumericQ
and Positive[x]
. I just don't have deep understanding of what the pattern is.
The condition, or test, is whether NumberQ[age]
returns True
, as I understand it now.