如何摆脱我的while循环

时间:2017-02-11 22:21:39

标签: python list for-loop while-loop

所以我的代码问题是,即使我输入了正确猜到的单词,我的代码仍然将其视为不正确;因此,请我再试一次。我怎么摆脱这个循环?欣赏它。

 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)

1 个答案:

答案 0 :(得分: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):

它会将您的列表转换回字符串。