我正在嘗試構建一個程序,該程序將爲用戶給出的每個輸入的每個輸入輸出一個參數名稱,直到幷包括31個參數。我有一個參數列表,每個參數都屬於一個特定數字,當用戶輸入一個數字結果是相應的參議員姓名。 當我運行該程序,不過,我不斷收到錯誤消息爲什麼我得到一個List索引超出範圍?
"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()
請幫助...謝謝。 =)
正確格式化你的代碼 –
'while district_number> = len(senator):''replace while'district_number> len(senators):' – Goat
'當你得到索引錯誤 – jramirez