我對python還是有點新的東西。最終目標是使用下面的代碼來搜索列表並打印列表中的每個grb.name。問題是我想使用用戶輸入,我遇到了問題,如果用戶輸入的日期不在列表中,它需要自動更正它,方法是添加一個日期,直到達到下一個grb_date,然後執行碼。這適用於start_date和end_date。使用while循環時出現KeyError
for i, grb in enumerate(results): #prolem with multiple grb's in 1 day
try:
grb_date = (re.sub('[A-Z]','',grb.name))
end_results = [i, grb_date]
data[str(grb_date)] = i # this is the important bit
# print (end_results)
except:
pass
#start_date = (input('What is the start date you want: '))
#end_date = (input('What is the end date you want: '))
while 1:
start_date = input('Please choose a start date: ')
end_date = input('Please choose an end date now: ')
try:
while data[start_date] <= data[end_date]:
print (results[data[start_date]].name)
data[start_date] += 1
except KeyError:
while data[start_date] not in end_results:
data[start_date] += 1
x = data[data[start_date]]
print ('Try using this date instead: %d'), x
這是我目前擁有的。我一直得到KeyError'111111'(或者如果它錯誤,則是任何start_date)。