How to grab and save many data entries in python?

Asked

Viewed 1,779 times

0

Guys I’m starting to program and so far the data inputs 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 above and store them "infinitely" and can for example save 30 names or 100 names along with the other information and request later.

  • Start by looking for repeat lists and loops (while), which is what you need to learn to solve this problem

1 answer

0


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

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

These values can be accessed through their position in the list (index), being 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 with an index name (key) instead of 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 in the list:

print pessoa['idade']
45

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

So you can answer your question with a program that’s more or less 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.

Browser other questions tagged

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