Python程序刚停止运行?

时间:2015-05-08 04:40:00

标签: python error-handling

while True:
    chunks = []

    for x in range(len(new_match_list)):
        if new_match_list[x] == ID_Input:
            chunks=[new_ID_info_list[x:x+7] for x in range(0, len(new_ID_info_list), 7)]

    if len(chunks) == 0:
        ID_Input = input("Please choose a number from the list provided, and enter it correctly this time!")

    if len(chunks) > 0:
        print (chunks[x])
        break

我的程序出现问题,显示没有错误,但突然停止运行,暂停一分钟,然后停止。

例如,程序在生成后停止:

Here is the list of complaint IDs you can choose from and ask about : ['1344139', '1344055', '1343332', '1343188', '1343131', '1341190', '1340441', ]
Choose a number from that list, and enter it in. Type in 'Quit' if you want to quit the program: 1344139

.....

没有任何错误信息产生。

代码的目标是打印出一个数据列表,其中包含有关特定ID号的7条信息(例如邮政编码,州)。

如果输入的身份证号码不在我的身份证号码列表中(AKA new_match_list),那么" chunks"将保持空白(因此,len(块)将为0),并且用户将被迫重新输入ID号,直到它与我的(new_match_list)上的ID号匹配。

如果ID号匹配,则应填写(块)并打印出与ID相关的(块)特定部分([x])。

我该怎么做才能解决此错误?

修改:我尝试了不同的方法来解决此错误,例如替换:

len(chunks) == 0:

if ID_Input not in new_match_list:

但没有任何效果。一如既往,程序停止而不会给我一个错误

1 个答案:

答案 0 :(得分:0)

您的问题有点不清楚,但我怀疑当控件达到print (chunks[x])时,您希望x获得new_match_list[x] == ID_Input True时的值。如果是,则需要将break语句作为if块的最后一行,即chunks=[new_ID_info_list...行之后。并且,正如Paul Cornelius所提到的,您需要更改该列表理解中的变量,以便x不被破坏。

但是,有一种更好的方法可以在列表中找到第一个匹配条目:使用其.index()方法。您需要将其置于try: ... except块内;或者,在尝试获取索引之前,使用in运算符测试ID是否在列表中。