0

I'm developing a small menu in python where at some point the user is being asked for a float number.

The user could pass:

1.23
1 //it's valid...
23.34e-10 //scientific notation

The user is asked for inserting a float value, if the value is not a float (for example the user could write a generic string...) the program doesn't have to crash but just to re-iterate until the user pass a valid float value. So actually the structure is

var = "";
while(var is not a float):
   var = raw_input("");

Does exists a fast way to do that? or should use somehow a regular expression?

user8469759
  • 2,522
  • 6
  • 26
  • 50
  • Most of them deal with try - except blocks... it's not what i want. – user8469759 Oct 01 '15 at 15:52
  • Also see http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – PM 2Ring Oct 01 '15 at 15:53
  • Why don't you want to use try - except? Exceptions in Python are quite efficient, and if the exception isn't raised a `try: ... except` is faster than an equivalent `if`. Of course, efficiency is irrelevant when you're waiting for user input in the terminal. :) – PM 2Ring Oct 01 '15 at 15:56
  • Because for what i'm doing i don't want the program terminate... is not a matter of efficiency. I mean i usually use try-except block for intermediate computation... not for input provided by the user by a menu. – user8469759 Oct 01 '15 at 15:57
  • Using try-except won't make the program terminate. See the first example in the accepted answer on the page I linked. That code uses try-except to test for a valid `int` but it's easy to adapt it to validate a `float`. – PM 2Ring Oct 01 '15 at 16:02
  • You right... i didn't know that. – user8469759 Oct 01 '15 at 16:07
  • If you want to know how to do this without try-catch, re-ask the question with that condition, and I can answer with a regular expression that captures valid FP strings. – Steve Hollasch Oct 02 '15 at 20:21

0 Answers0