为什么我的List索引超出范围?

时间:2013-10-30 16:20:52

标签: python list

我正在尝试构建一个程序,该程序将为用户提供的数字的每个输入输出参数名称,直至并包括31.我有一个参与者列表,每个参与者都属于一个特定的数字,当用户输入一个数字结果是相应的参议员姓名。 但是,当我运行程序时,我不断收到错误消息

"Index Error: List index out of range".

我做错了什么?这是代码:

def main():
    senators = ['Kevin Eltife', 'Bob Deuell','Robert Nichols', 'Tommy Williams',
                'Charles Schwertner', 'Sylvia Garcia', 'Dan Patrick', 'Ken Paxton',
                'Kelly Hancock', 'Wendy Davis', 'Larry Taylor', 'Jane Nelson',
                'Rodney Ellis', 'Kirk Watson', 'John Whitmire', 'John Carona',
                'Joan Huffman', 'Glenn Hegar', 'Carlos Uresti', 'Juan "Chuy" Hinojosa',
                'Judith Zaffirini', 'Brian Birdwell', 'Royce West', 'Troy Fraser',
                'Donna Campbell', 'Leticia Van de Putte', 'Eddie Lucio, Jr.',
                'Robert Cuncan', 'Jose Rodriguez', 'Craig Estes', 'Kel Seliger']

    district_number = int(input('Give the senator''s district number (enter 0 to end): '))
    while district_number > len(senators):
        print('That district number does not occur in Texas.')
        district_number = int(input('Enter another valid district number (enter 0 to quit): '))

    while district_number != 0:
        print('That district is served by the honorable ', senators[district_number - 1], '.', sep='')
        district_number = int(input('Enter another district number (enter 0 to quit): '))

# Call the main function.
main()

请帮忙......谢谢。 =)

3 个答案:

答案 0 :(得分:2)

第一次输入小于31后,您将进入一个不再检查最大区号的循环。所以序列说20然后40将导致索引错误。

答案 1 :(得分:1)

首先,我建议不要使用列表。如果你使用字典,你可以使用get()方法,只需检查它是否返回结果。虽然我不专业,但在我看来,这似乎是一种最佳实践。这是一个例子。

SENATORS = {1: 'Kevin Eltife', 
            2: 'Bob Deuell',
            3: 'Robert Nichols', 
            4: 'Tommy Williams',
            5: 'Charles Schwertner', 
            6: 'Sylvia Garcia', 
            7: 'Dan Patrick'}

while True: # loop until program is exited
  district_number = int(input('Give the senator''s district number (enter 0 to end): '))
  senator = SENATORS.get(district_number) # Will return None if user enters invalid number
  if senator:
    print('That district is served by the honorable ', senator, '.', sep='')
  else:
    print('That district number does not occur in Texas.')

在我看来,这不仅更容易阅读,而且如果你需要将来更容易编辑,并消除用户错误(除非他们当然键入“duck”或“棒球”,在这种情况下你的int()调用会非常生气。

答案 2 :(得分:0)

那是因为您直接使用了索引编号:

print('That district is served by the honorable ', senators[district_number - 1], '.', sep='')

你应该把它放在try/except块附近:

while district_number != 0:
    try:
        print('That district is served by the honorable ', senators[district_number - 1], '.', sep='')
    except IndexError:
        print("District Number too high")
    district_number = int(input('Enter another district number (enter 0 to quit): '))

控制台会话:

Give the senators district number (enter 0 to end): 22
That district is served by the honorable Brian Birdwell.
Enter another district number (enter 0 to quit): 100
District Number too high
Enter another district number (enter 0 to quit):