如何摆脱我的while循环

2024-04-19 01:45:17 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我的代码的问题是,即使我输入了正确猜出的单词,我的代码仍然将其读取为不正确的;因此,请我再试一次。我怎样才能摆脱这个循环?谢谢你。你知道吗

 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)

Tags: to代码inputcountrandomlengthlistword
1条回答
网友
1楼 · 发布于 2024-04-19 01:45:17
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):

它会将您的列表转换回字符串。你知道吗

相关问题 更多 >