How to repeat the code at the end in python?

3

So, I'm starting programming (just by appending it myself) and wanted to know how to do code to restart at the end.

I know it may seem like something simple but I do not take any courses, I'm learning alone

lanchonete = ("500$")

açaiteria = ("900$")

uber = ("200$")

pationorte = ("1200$")

pergunta = input ("Diga o nome do estabelecimento desejado ")

if pergunta ==("lanchonete"):
   print (lanchonete)

elif pergunta ==("açaiteria"):
   print (açaiteria)

elif pergunta ==("uber"):
   print (uber)

elif pergunta ==("pationorte"):
   print (pationorte)

else:
   print ("Este estabelecimento não esta cadastrado no nosso banco de 
   dados")
    
asked by anonymous 17.04.2018 / 03:33

2 answers

5

Since you are learning, it is worth commenting. What you did in your code basically was to relate four variables to their respective values and, at first, will not vary during execution. Something like this is usually called a map: you define a direct relationship between a key and a value. In this case, the key would be the name of the establishment and the value of the related monetary amount. In Python, the simplest way to implement this is with the dictionary:

estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

To get the value from a key, just use the get method, which even allows you to set a default value if the key does not exist:

padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'
pergunta = input("Diga o nome do estabelecimento desejado ")
print(estabelecimentos.get(pergunta, padrão))

Putting this inside a loop of repetition would be:

estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'

while True:
    pergunta = input("Diga o nome do estabelecimento desejado ")
    print(estabelecimentos.get(pergunta, padrão))

See working at Repl.it

    
17.04.2018 / 04:51
1

Just wrap your code in a while True loop.

The while checks a condition, and if it is true, it executes everything inside its indentation block again. As we pass True , it will always execute all over again.

As another tip: parentheses are unnecessary in cases of assignment ( = ) and comparison ( == ), and are only needed here for functions. Your code gets a little clearer without them!

while True:
    lanchonete = "500$"

    açaiteria = "900$"

    uber = "200$"

    pationorte = "1200$"

    pergunta = input ("Diga o nome do estabelecimento desejado ")

    if pergunta == "lanchonete":
       print (lanchonete)

    elif pergunta == "açaiteria":
       print (açaiteria)

    elif pergunta == "uber":
       print (uber)

    elif pergunta == "pationorte":
       print pationorte

    else:
       print ("Este estabelecimento não esta cadastrado no nosso banco de dados")
    
17.04.2018 / 03:39