2017-02-11 100 views
0

所以我的問題與我的代碼是,即使我已輸入正確的猜測詞,我的代碼仍然讀取它不正確;因此,請我再試一次。我如何擺脫這個循環?欣賞它。如何擺脫我的while循環

import random 

count = 1 
word = ['orange' , 'apple' , 'chicken' , 'python' , 'zynga'] #original list 
randomWord = list(random.choice(word)) #defining randomWord to make sure random 
choice jumbled = "" 
length = len(randomWord) 

for wordLoop in range(length): 

    randomLetter = random.choice(randomWord) 
    randomWord.remove(randomLetter) 
    jumbled = jumbled + randomLetter 

print("The jumbled word is:", jumbled) 
guess = input("Please enter your guess: ").strip().lower() 

while guess != randomWord: 
     print("Try again.") 
     guess = input("Please enter your guess: ").strip().lower() 
     count += 1 
     if guess == randomWord: 
     print("You got it!") 
     print("Number of guesses it took to get the right answer: ", count) 
+2

break存在一個循環 – Nullman

+0

這是一個關於for循環的問題的重複,這裏的這個問題是關於while循環的嗎?更重要的是這個問題甚至沒有關於退出while循環。它應該是「爲什麼我的條件總是評估真實」。 – shove

+0

@shove您可以投票重新打開。閉幕審查是https://stackoverflow.com/review/close/15181216 –

回答

0
randomWord.remove(randomLetter) 

這條線將刪除您的變量的每一個字母。 您可以使用:

randomWord2 = randomWord.copy() 
for wordLoop in range(length): 
    randomLetter = random.choice(randomWord2) 
    randomWord2.remove(randomLetter) 
    jumbled = jumbled + randomLetter 

這將複製您的變量。如果你不這樣做,你的結果將是同一個變量的兩個名稱。

你比較字符串列表試試這個來代替:

while guess != ''.join(randomWord): 

將列表轉換回一個字符串。