2016-05-13 36 views
0

我想讓hang子手,我知道還有很多事情要做,但我無法弄清楚爲什麼底部的異常不起作用。這是我的代碼。爲什麼我的例外不起作用

import random 
hideword = 0 
player1 = input('''What is player 1's you name? ''') 
player2 = input('''What is player 2's you name? ''') 
letterlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k' ,'l' ,'m' ,'n' ,'o' ,'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 
print(player1 + 'is first!') 
word = input(player2 + ', please turn away, ' + player1 + ' please write a LOWER case word for ' + player2 + ' to guess. ') 
wordsplit = list(word) 
while hideword < 50: 
    print() 
    hideword += 1 
while True: 
    print(player2 + ', ' + player1 + ''''s word fits into these blanks''') 
    print('_ ' * len(wordsplit)) 
    letter = input(player2 + ' please type a LOWER case letter to guess. ') 
    wordsplit.index(letter) 
    letterlist.remove(letter) 
    try: 
     if letter in wordsplit: 
      print('CORRET!') 
      print('_ ' * wordsplit.index(letter) + letter + ' _ ' * (len(wordsplit) - wordsplit.index(letter) - 1)) 
      break 
    except ValueError: 
     print('Incorrect! Try again') 
+2

如果你的'try:except:'塊,那麼會導致'ValueError'? –

回答

0

那麼,在try區塊內沒有任何東西可以拋出豁免,處理您的情況的最佳方法可能是按照建議使用if..else

然而,一個異常已經可以在這些線路上拋出:

wordsplit.index(letter) 
letterlist.remove(letter) 

這是你如何能使其與try..except工作(只是作爲一個例子,因爲if..else也適用):

letter = input(player2 + ' please type a LOWER case letter to guess. ') 

try: 
    position = wordsplit.index(letter) 
    letterlist.remove(letter) 
    print('CORRECT!') 
    print('_ ' * position + letter + ' _ ' * (len(wordsplit) - position - 1)) 
    break 

except ValueError: 
    print('Incorrect! Try again') 
1

您需要else那裏,而不是try..except。後者適用於那些會導致程序崩潰的事情。正如你在程序中那樣檢查成員資格不會導致這樣的錯誤。

try: 
    if letter in wordsplit: 
     print('CORRET!') 
     print('_ ' * wordsplit.index(letter) + letter + ' _ ' * (len(wordsplit) - wordsplit.index(letter) - 1)) 
     break 
except ValueError: 
    print('Incorrect! Try again') 

更改爲:

if letter in wordsplit: 
    print('CORRET!') 
    print('_ ' * wordsplit.index(letter) + letter + ' _ ' * (len(wordsplit) - wordsplit.index(letter) - 1)) 
    break 
else: 
    print('Incorrect! Try again') 
+0

嗯,我試過了,我的代碼如下所示:if letterplot: print('CORRET!') print('_'* wordsplit.index(letter)+ letter +'_'*(len(wordsplit) - wordsplit.index(letter) - 1)) break else: print('Incorrect!Try again')但是當我運行代碼並輸入不在列表中的東西時,它仍然給我一個錯誤! – Maximus

+0

請參閱我對此問題的回答。 – Keiwan

0

當你正在檢查:if letter in wordsplit,你有沒有養ValueErrorwordsplit.index(letter)的機會。

因此,不需要引發錯誤。 如果letter not in wordsplit,就跟上else一樣,如前所述。