How do I get and save many data entries in python?

0

I'm starting to program and so far the data entries were like this:

    dado_1 = str(input('Seu nome: '))
    dado_2 = int(input('Sua idade: '))
    dado_3 = str(input('Sexo: '))

But I was left with a doubt, as I take the same data as above and store it in an "infinite" way, for example saving 30 names or 100 names along with the other information and requesting later.     

asked by anonymous 13.06.2018 / 01:00

1 answer

0

Variables of the same type can be aggregated into a list (I'll use Python terminology ), for example:

animais=['cachorro', 'gato', 'galinha']
print(animais)
['cachorro', 'gato', 'galinha']

These values can be accessed through their position in the list (index), the first item starting at zero.

print(animais[2])
'galinha'

And new values can be easily added:

animais.append('porco')
print(animais[3])
'porco'

You can also have lists that can be indexed by a name (key), rather than by a numeric value. In Python they are called dictionaries:

pessoa = { 'nome': 'Giovanni', 'idade': 45, 'sexo': "M" }
print(pessoa)
{'idade': 45, 'sexo': 'M', 'nome': 'Giovanni'}

And each value accessed as such in the list:

print pessoa['idade']
45

In this case the order is not preserved since you access the values by the key. And the interesting thing is that you can store any key / value pairs within the dictionaries.

So you can answer your question with a program that looks something like this:

#!/usr/bin/python3

# lista com as pessoas, vazia por enquanto.
pessoas = []

# coloquei apenas 5 para não ficar cansativo mas pode ser qualquer valor.
for i in range(5):
    nome = input('Nome : ')
    idade = int(input('Idade : '))
    sexo = input('Sexo : ')

    # cria um dicionário com o que foi entrado e adiciona à lista.
    pessoas.append({ 'nome': nome, 'idade':idade, 'sexo':sexo })

# e para cada pessoa armazenada...
for pessoa in pessoas:
    # recupera de pessoa tanto 'chave' como 'valor'.
    for chave, valor in pessoa.items():
        print("{} => {}".format(chave, valor))
    print("----")

Of course, these values will be in memory only while the program is running, being discarded as soon as it is finished.

This is a very basic explanation and it is worth reading about these two types of data to, among other things, know the other methods and attributes that can be used to work with their content.

    
13.06.2018 / 02:02