One of the first things to consider is adding the pair to the variable dic
only after the break
, After all, if you’re going to use 9999 as an output, it’s not for 9999
enter the dictionary, mainly due to the fact that split
not divide the 9999
in two parts.
Another thing is that entrada
has to be compared with '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
Of course, this only serves as an exercise, because the ideal would be to protect the code by sanitizing the entrances, instead of letting the error.
A simple example of how to protect the entrance (and optimizing the 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
where this declared the variable
dic
?– gato
put the rest of your program code.
– gato
First line added.
– Guilherme Santana De Souza
the loop will continue while the user informs values other than 9999, this should be an infinite loop, vc does not need the variables
zero
andum
, just putwhile(true)
orwhile(1)
that are endless loops, and get out of the loop with break.– gato
But what would be the condition to get out of the loop?
– Guilherme Santana De Souza
When input equals 9999.
– gato
what mistake you get?
– gato
Does not work. I get the error: dic[list[1]] = list[0] Indexer: list index out of range
– Guilherme Santana De Souza
Vc must specify the correct key for your dictionary, to determine the value according to the key position.
– gato
I don’t understand. The program should not understand since I am using the input as a condition for break?
– Guilherme Santana De Souza