2017-02-11 101 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): 

将列表转换回一个字符串。