Python data entry with multiple lines

Asked

Viewed 3,082 times

1

I would like to understand how to input several data (int, float, str...) per line but repeatedly (i.e., in several lines) so that I can save each given input.

I understand that I will have to use a list to store each input and, using split, I can input several data on the same line, but I get lost when it comes to doing this with several lines.

For example:

linha = input().split()

lista = []
for item in range(5):
    x = int(linha[item])
    lista.append(x)
print(lista)

This code gives me a line with several input data (integers), I would like to repeat this process in as many lines as I want and with the various types of data I want. However, as a beginner, I’m still not used to the syntax.

  • "how many lines I want" is easy and can be explained... Now "with the various types of data I want" needs to be clarified... How would you decide what type of data should be the user input?

  • "How would you decide what type of data the user input should be? " Suppose the problem asks for something like "an int followed by a string", for example. "easy and can be explained." would be very grateful for the explanation.

  • I’m trying to understand your problem to formulate a proper answer :D ... Then it will be pre-determined how many inputs the user will enter and what types of each input?

  • That’s right. I’ll try to break my problem] in steps. 1 - Let’s assume I pre-determine the range first. For example. It will be x lines with y characters on each line. 2 - These characters can be int, float, strings... 3 - Need to store the data of each row in a list.

2 answers

2


The function input() always returns a string, to work with other types of data we need to manipulate this string, so let’s go by parts.


Receive multiple values

We can solve this problem with different approaches, example:

Getting all values at once.

We can receive a string with all values separated by whitespace and use the method str.split() to "break" this string into a list of strings. Example:

linha = input("Digite os valores separados por espaço")
# ex.: '1 2 3 4 5'
valores = linha.split()
# ['1', '2', '3', '4', '5']

If you want to convert all values to integer you can use:

  • A for to iterate on the values, convert the value and then add to the result list with list.append().

    linha = input("Digite os valores separados por espaço")
    valores = []
    
    for valor in linha.split():
        valores.append(int(valor))
    
  • The function map to apply a function to all items of an iterable and create a new list with the function result for each position of the list.

    linha = input("Digite os valores separados por espaço")
    valores = linha.split()
    valores_convertidos = map(int, valores)
    
  • One comprehensilist on to iterate and convert all values:

    linha = input("Digite os valores separados por espaço")
    valores = linha.split()
    valores_convertidos = [int(valor) for valor in valores]
    

Receiving one value at a time

You can receive an indefinite number of inputs using a loop and setting a stop criterion.

For example, receive integer numbers while the user enters valid values:

valores = []

while True:
    try:
        linha = int(input("Digite um número:"))
    except ValueError:
        print("Valor inválido, saindo do loop")
        break

    valores.append(linha)

In the above code I am creating an "infinite" loop that will be repeated while converting user input to int not fail. When it fails it will launch a ValueError running the break within the except


Receiving a specific number of variables with predefined types

You can receive a specific number of inputs using the function range() as you yourself posted in your question:

valores = []

for _ in range(5):
    valor = input("Digite algo: ")
    valores.append(valor)

The next step is to define the types of data we should receive. We could use whole numbers or even strings to define data types.

Example:

# 0: int
# 1: str
# 2: float
tipos = [0, 1, 1, 0, 2]
valores = []

for tipo in tipos:
    valor = input("Digite algo: ")

    if tipo == 0:
        valores.append(int(valor))
    elif tipo == 1:
        valores.append(valor)  # já é string
    elif tipo ==2:
        valores.append(float(valor))
    else:
        print("Tipo inválido, nenhum valor adicionado")

I won’t go into too much into the improvements that could be made in the above code as it is only a demonstration of how it could be done.

Instead of having several if for each type you would like to have, you could use a list of functions that receive a string and return the type you want. In python, functions are "first-class citizens", this means that you can pass them as parameters to other functions, assign them to variables, etc...

So it’s possible to do something like:

meu_int = int
valor = meu_int("10")
print(valor)  # 10

Applying this concept, remaking the example and removing the if would be:

tipos = [int, str, str, int, float]
valores = []

for tipo in tipos:
    valor = input("Digite algo: ")
    valores.append(tipo(valor))

Code running on Repl.it

This way you are specifying that you want the user to enter 5 values, namely an integer, 2 strings, 1 integer and 1 float, respectively. Not to mention that you can create your own functions or classes that receive a string as input and return an object of the type you want.

Completion

As the subject is generic, it turned out that the answer got a little wide, but the important thing is that you understand that there are several approaches to the same problem and I hope to have given enough material for you to have a starting point for new studies and new questions.

  • Fernando, in fact, his answer satisfied absolutely everything I needed. Honestly, I don’t know how to thank you, for that really helped a lot. Thank you so much!

  • The intention is to really help, I’m glad it worked out. If my answer satisfied absolutely everything you needed, consider marking it as accepted. I don’t say this because of point of reputation, it’s more because someone will fall on this page with the same doubts in the future and if that’s how you think it would make more sense for the future visitor understand that this answer was more useful to your question.

  • As I am new here, I had not yet noticed these details. Marked as accepted. Thanks!

0

Abuse and use of try

texto = '''1
teste
1.5
balb
512

1,4'''
# Separa String por linhas e cria uma lista
lst = texto.split('\n')

lst_tratada = []
# Para cada valor que estiver na lista
for i in lst:
    # Tenta registrar o valor como int e vai para o próximo laço, senão continua
    try:
        lst_tratada.append(int(i))
        continue
    except:
        pass
    # Tenta registrar o valor como float e vai para o próximo laço, senão continua
    try:
        lst_tratada.append(float(i))
        continue
    except:
        # Se não conseguir nenhum dos dois, tratar como string
        lst_tratada.append(i)

print(lst_tratada)

A simpler approach, from a method:

def var_parser(x):
    try: # Tenta retornar x como inteiro
        return int(x)
    except: # Se não obtiver exito, continuar
        pass
    try: # Tenta retornar x como float
        return float(x)
    except: # Se não obtive exito, retornar x 
        return x


texto = '''1
teste
1.5
balb
512

1,4'''

lst = texto.split('\n')

lst_tratada = []
for i in lst:
    lst_tratada.append(var_parser(i))

print(lst_tratada)
  • did not get to be exactly what I need. Or, unfortunately, I did not understand your answer. In this case, I myself will provide the data and they will be several per line and will be several lines (with various data). But I found it interesting the use of split(' n'). I’m trying to see how to use it. Thanks!

  • It is quite simple. First it tries to register in the list as int, if it fails it tries as float, and if it fails again it registers as string. Now the split(' n'), type... The line jump is recorded as n, so we use split(' n') to separate by line. Even python print() always puts at the end of the line ' n', so the terminal will always go to the next line after using the print function()

  • Ahhhh, it’s clear now. I’ll try to implement in my case and see if it works, thank you!

  • I recommend you take a look at Try and Except. They are great for both error treatment and logic testing, which was used in this example.

Browser other questions tagged

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