Variable creation via Python user response

Asked

Viewed 1,165 times

0

I would like to make the user insert a response from that answer would create a "variable" or not. I do not know if creating a new variable would be the best way, follow example:

a = str(input('Existe mais produtos para serem adicionados?: '))

In this part the user would respond yes or nay, if the answer were yes, the program would create another variable that would receive a certain value float (a2 A3 A4) and so on.

  • Unfortunately what you are looking for in the code doesn’t make much sense. What would you do with such variables a2 a3 a4 ?

2 answers

1

The user create is not possible like this. But here I have a solution

a= str (input ('Existe mais produtos para serem adicionados?: '))
a2 = 0
a3 = 0
a4 = 0
if a == 'sim':
    a2 = 1
else:
    a3 = 1

But I imagine the best in your code would be a list. Something like that:

lista = []
a= str (input ('Existe mais produtos para serem adicionados?: '))
if a == 'sim':
   lista.append(1) #valor

So, if you put inside a while, changing what you put inside the append, and changing the if, you can make an infinite list, which I think is what you want, then you run the while, while the answer is different from 'no'. If you need help on how to do it, leave the code, or specify what you want, I’ll be happy to help.

0


I would recommend that you use dictionaries. So you can track the value by the item name, for example. If you wanted to run a while until there were no more products to add, just use the following code.

 #criamos nosso dicionario
d={}
a = "s"
#utilizei o lower pra sempre deixar a resposta em minusculo, pra nao ter problemas com input maiusculo
while a.lower() == "s":
    item = input("Digite o item que deseja adicionar")
    valor = float(input ("Digite o valor do item %s: "%item))
    d[item] = valor
    a = input ("Deseja adicionar mais algum item? s/n")
#para exibir em for, utilizamos a seguinte sintaxe
for x in d:
    #como o x vai rodar sempre com o valor da chave (nome), podemos chamar o valor do preço com a o dicionario[x] (d[x])
    print ("Item: %s \tPreço: %.2f"%(x, d[x]))

Browser other questions tagged

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