How to allow input() to receive scientific notation in python 3?

Asked

Viewed 103 times

-2

I have a thermal expansion coefficient that the user must provide, example 1.6*10e-5, exactly this value, how to allow the user to write this value in scientific notation?

input of the coefficient by the user

notação = input('digite a notação')

operation

multiplica_n = notação * 2

Print(str(multiplica_n))
  • It makes no sense to modify the question since a small variation of the answer solves the new problem: str_value = str_value.replace("*10", "").

1 answer

2

The normal call to turn a string to decimal number - float, already converts any valid Python number to a "float" object that is treated as a number.

And valid numbers include numbers with . decimal, "-" sign, exponent of scientific notation with "e" or "E", and the literals "inf" and "Nan" - but do not include the time sign with the letter "X" (nor with the Unicode character " (N-ARY TIMES OPERATOR"), which is different from the letter "X"). That is, you can pass "1.6e-5", but it does not understand "1.6X10e-5" - this would already be an explicit account of times.

It is important to keep in mind that in the case of an invalid number the call to floatwill give an error of type "Valueerror" - in this case it is important to combine a block try/except along with a block while to repeat the input.

So, as examples: a = '2e5' creates a string - if we follow this with print(float(a)), let’s see Python interpret "e" as the "e" of scientific notation:

In [97]: a = "2e5"                                                                                                           

In [98]: print(float(a))                                                                                                     
200000.0

('In[...]' and 'Out[...]' are the Ipython prompt in interactive mode)

The call to input always returns a string (in Python 3 - in the old versions of the language, until 2.7, it was necessary to use the raw_input)

If you want the "X" symbol as the times operator to be used, you can make a transformation before the call to float to take the letter from the string - so even if the user enters the number, the input remains valid. For this, it is possible to use the method .replace of strings.

Finally, if you are going to validate the entry with the while/try/except it is worth putting the whole code snippet into a function - so that this code can be reused for any float input.

def float_input(msg=""):
    retry = True
    while retry:
        str_value = input(msg)
        str_value = str_value.replace("X10", "").replace("x10", "")
        try:
            value = float(str_value)
        except ValueError:
            pass
        else: 
            # Esse else é do bloco "try": só entra aqui quando não ocorrer erro na chamada ao `float()"
            retry = False
    return value

And you can use it like this:

In [104]: v = float_input("Digite a notação: ")                                                                              
Digite a notação: 1.6X10e-5

In [105]: print(v)                                                                                                           
1.6e-05

In [106]: print(v * 2)                                                                                                       
3.2e-05

Browser other questions tagged

You are not signed in. Login or sign up in order to post.