How to define which inputs will be accepted by the code?

Asked

Viewed 87 times

1

I have a code where as the user enters data, I want to create a list that will be used for operations later. Output input would be the key "f" interrupting the repeat structure and initiating operations with the list.

My doubt is how I do so that if the user has not entered a number is it float or int or the key "f", generates a message and that this value does not enter the list as a string ?

Example: In the code below, I can get to where I wanted but if I type any different value of number or key "f", the list will be generated anyway with the unwanted values within it.

list = []
number = -1

while number != 'f':
    number = (input())
    list.append(number)

    if number == 'f':
        list.remove('f') 
        break

print(list)
  • 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.

  • 1

    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 to 1_000.123_4 that had turned 1000.1234 - see. If you want to accept only numbers in a given format, then regex (suggested in another answer) will restrict more possible values.

2 answers

2

Just use a try-except to try to convert the string into a float. If the conversion is not possible, a ValueError and this will mean that the value entered was not numerical.

See below how the code would look:

number_list = [] # Lembre-se que o nome "list" já existe em Python.

while True:
    number = input("Digite um número: ")
    if number.lower() == "f": break

    try:
        number = float(number) # Converte para float
        number_list.append(number)
    except:
        print("Você deve digitar um valor numérico.")

print(number_list)
  • 1

    MUITOOOOOOOOOOO THANKS !!! saved my day bro, vlw even.

2

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

  • Thank you very much, I will update the code. These reports were very helpful.

Browser other questions tagged

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