How to stop a loop using the input provided by the user?

2

I am writing a program that receives entries and creates a dictionary from them. I need the loop that I use to insert the entries in the dictionary to be broken when the entry is "9999", but it is not working. I'm doing this: dic = dict ()

dic = dict()
gabarito = raw_input()
um = 1
zero = 0
while zero < um:
    entrada = raw_input()
    lista = entrada.split()
    dic[lista[1]] = lista[0]
    if entrada == 9999: 
        break
print dic

What's wrong? How to proceed?

    
asked by anonymous 17.04.2016 / 15:27

1 answer

3

One of the first things to consider is to add the pair to the variable dic only after break , after all, if you use 9999 as output, it is not for 9999 to enter the dictionary, fact that split does not split 9999 into two parts.

Another thing is that entrada has to be compared to '9999' instead of 9999 , by entering as string :

dic = dict()
gabarito = raw_input()
um = 1
zero = 0
while zero < um:
    entrada = raw_input()
    lista = entrada.split()
    if entrada == '9999': 
        break
    dic[lista[1]] = lista[0]
print dic

Obviously this is only an exercise, because the ideal would be to protect the code by sanitizing the inputs instead of letting them go wrong.

A simple example of how to protect the input (and optimizing while ):

dic = dict()
gabarito = raw_input()
while True:
    entrada = raw_input()
    lista = entrada.split()
    if entrada == '9999': 
        break
    elif len(lista) < 2:
        print 'forneca dois valores, ou 9999 para sair'
    dic[lista[1]] = lista[0]
print dic
    
17.04.2016 / 17:04