我目前正試圖編寫一個迭代序列(x)的代碼,搜索用戶輸入的單詞。異常發生甚至值是真的?
以下是代碼。
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
i = -1
while True:
s = input("Enter a word to search: ")
if s != "Quit":
try:
while i < len(x):
i = x.index(s, i+1)
print("found at index", i)
except ValueError:
print("Not found")
i = -1
else:
break
print("Goodbye")
上面的代碼通過迭代工作正常,但通過序列迭代後總是返回ValueError異常。我試圖通過添加進行整治:
while i < len(x):
思維一旦到達序列末尾的迭代將停止,但繼續從序列返回找到的值後拋出異常。
例如,如果用戶輸入「9」,什麼是返回是:
found at index 8
Not found
謝謝!這個答案是完美的,像魅力一樣工作。雖然我也通過改變'while(i
Keith
2013-04-25 21:25:20
實際上,第一種方法是完美的,但第二種方法對所有搜索產生-1索引的結果。 – Keith 2013-04-25 22:46:04
哪種方法? 'found'標誌,列表理解用'enumerate()'或簡單的'.index()'表示第一次匹配? – 2013-04-25 22:50:41