Message Boards Message Boards

0
|
4964 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Ensure that inputs are entered as numeric value

Posted 3 years ago

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.

POSTED BY: Ehud Behar
3 Replies

You might also consider looking into FormFunction[{"x" -> "Number"}] or InputField[__, Number]

POSTED BY: Kyle Keane
Posted 3 years ago

Ehud:

What you came up with looks like a reasonable solution.

What do you not like about it?

If you would rather not use If[], then you can use pattern matched functions. Something like:

respond[age_?NumericQ] := "You are " <> ToString[age] <> " years old.";
respond[_] := "Please enter a number for your age.";

age = InputString["What is your age?"];
Print[respond[ToExpression[age]]];

Have a great and safe holiday.

POSTED BY: Mike Besso
Posted 3 years ago

Be careful with using ToExpression, it can be used to execute arbitrary code that could be dangerous. An innocuous example

ToExpression["EmitSound[Sound[SoundNote[]]]"]

A safer way would be to use Interpreter[Integer].

Interpreter[Integer]["15"]
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract