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.
"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?
– fernandosavio
"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.
– zangs
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?
– fernandosavio
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.
– zangs