An alternative solution would be to create a regular expression to validate the input as an integer or floating point number and then use the method ast.literal_eval()
to obtain the literal value of the input.
Despite the name literal_eval()
remember the infamous eval()
, the method literal_eval()
is safe because it does not allow analyzing complex expressions (no code injection) it is a specific evaluator for literals and analyzes strings
, bytes
, números
, tuplas
, listas
, dicionários
, sets
, booleanos
, and None
The regular expression I picked up ready this reply in the Stack Overflow EN and adapted to the code:
from re import compile; # Para compilar a expressão regular
from ast import literal_eval; #Para avaliar o literal
result = [] #Lista de resultados
#Fonte: https://stackoverflow.com/a/385597/11379709
re_float = compile("""(?x)
^
[+-]?\s* # Que inicialmente, corresponda a um sinal opcional seguido ou não de espaço(s)
(
\d+ # Ou corresponde a um ou mais digitos...
(\.\d*)? # ...seguido(s) ou não de um ponto e zero ou mais digitos
|\.\d+ # Ou um ponto seguido de dígitos
)
([eE][+-]?\d+)? # Podendo ou não ter a notação exponencial
$""")
while True:
print("Digite um número ou f para sair:")
entrada = input()
if entrada.upper() == 'F': break; #Se a entrada for f ou F abandona o laço
entrada = re_float.fullmatch(entrada) #Tenta validar a entrada como numérico
if entrada:
#Se houver exito na validação
result.append(literal_eval(entrada.group(0))) #Adiciona o valor literal da entrada na lista de resultados
else:
#Caso não haja exito na validação
print("Entrada inválida...")
print(result)
Test the code on Repl.it
If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.
– Augusto Vasques
It depends on what you want to accept as a valid input. Use
float
(as one of the responses suggested), it will also accept strings as'inf'
and'nan'
(respectively become "infinity" and "not a number"), in addition to1_000.123_4
that had turned1000.1234
- see. If you want to accept only numbers in a given format, then regex (suggested in another answer) will restrict more possible values.– hkotsubo