2014-09-27 51 views
0

在這個例子中,我們將設置PH[0]'Ten of Hearts',並guess'Ten'「雖然不是」錯誤 - 蟒蛇

名單「PH」表示去魚的紙牌遊戲玩家的手。當用戶猜測一張卡片時,他們必須猜出一張與他們手中的卡片相對應的卡片。我寫了這個代碼塊,以便如果用戶輸入一個無效猜測(如果猜測不在PH,他們會再次提示輸入一個新的猜測)

我覺得我有問題的變量在數組[guess1, guess2, guess3, guess4],但我不太確定。

執行代碼時,循環會一直持續。我需要能夠退出循環以便返回猜測,以便它可以輸入到下一個函數中。

如果有人能幫我解決我遇到的問題。

guess = str(raw_input("Make a guess : ")) 

guess11 = guess, 'of Hearts' 
guess1 = " ".join(guess11) 

guess22 = guess, 'of Diamonds' 
guess2 = " ".join(guess22) 

guess33 = guess, 'of Clubs' 
guess3 = " ".join(guess33) 

guess44 = guess, 'of Spades' 
guess4 = " ".join(guess44) 

while PH[0] not in [guess1, guess2, guess3, guess4] : 
    print "You do not have a card like that in your hand." 
    guess = str(raw_input("Make another guess : ")) 

    guess11 = guess, 'of Hearts' 
    guess1 = " ".join(guess11) 

    guess22 = guess, 'of Diamonds' 
    guess2 = " ".join(guess22) 

    guess33 = guess, 'of Clubs' 
    guess3 = " ".join(guess33) 

    guess44 = guess, 'of Spades' 
    guess4 = " ".join(guess44) 

return guess 
+5

該代碼傷害了我的眼睛!瞭解如何撰寫[DRY](http://en.wikipedia.org/wiki/Don't_repeat_yourself)代碼。它會讓你的生活變得更容易。 – Basic 2014-09-27 23:17:01

+0

當我將'PH [0]'設置爲''''十'心'和'猜'到''''時,它對我有用。該循環正確退出。 – interjay 2014-09-27 23:18:17

+0

'raw_input'已經是一個字符串 – 2014-09-27 23:20:41

回答

1

您只是在測試如果玩家手中的第一張牌是任何的他猜測。你需要測試每張牌的牌:

while not any(guess in PH for guess in [guess1, guess2, guess3, guess4]): 

這需要每個猜測卡和測試卡反對手。 any()在找到匹配時停止循環猜測。

一個更好的想法仍然是使用一套十字路口:

guesses = {guess1, guess2, guess3, guess4} 
while not guesses.intersection(PH): 
    # ask for new guesses 

你想避免鍵入您的「要求猜測」代碼兩次;開始一個循環與while True和使用break結束循環時,正確的猜測已經取得:

suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades') 

while True: 
    guess = raw_input("Make a guess:") 
    guesses = {'{} of {}'.format(guess, suit) for suit in suits} 
    if guesses.intersection(PH): 
     # correct guess! 
     break 
    print "You do not have a card like that in your hand." 

我用了一套理解建立在猜測的循環。

+1

@EvanCooper:但您的'while'循環不會結束,直到'PH [0]'中有匹配的卡。那些其他部分將永遠達不到。 – 2014-09-27 23:17:12

+0

好了,現在我明白了。非常感謝 – 2014-09-27 23:41:05