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

Asked

Viewed 4,199 times

2

I’m writing a program that receives entries and creates a dictionary from them. I need the loop I use to insert the entries in the dictionary to be broken when the entry is "9999", but it is not working. I am doing as follows: 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 is wrong? How to proceed?

  • where this declared the variable dic?

  • put the rest of your program code.

  • First line added.

  • 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 and um, just put while(true) or while(1) that are endless loops, and get out of the loop with break.

  • But what would be the condition to get out of the loop?

  • When input equals 9999.

  • what mistake you get?

  • Does not work. I get the error: dic[list[1]] = list[0] Indexer: list index out of range

  • Vc must specify the correct key for your dictionary, to determine the value according to the key position.

  • I don’t understand. The program should not understand since I am using the input as a condition for break?

Show 5 more comments

1 answer

3


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

Browser other questions tagged

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