0

我正在尝试构建一个程序,该程序将为用户给出的数字的每个输入输出一个参议员姓名,最多包括 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()

请帮助...谢谢。=)

4

3 回答 3

2

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

于 2013-10-30T16:38:49.273 回答
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.')

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

于 2013-10-30T16:49:12.353 回答
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): 
于 2013-10-30T16:29:28.693 回答