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