Python 猜单词游戏代码优化
There are a few issues with your code.
First, the function guess() is not defined correctly. It should have parameters word1 and word2, and it should return the shuffled word and the original word. Additionally, the function should be called with the correct arguments when using it in the while loop.
Second, the variable ture should be True instead of ture.
Finally, you are not breaking out of the while loop when the word is guessed correctly. You need to use the break keyword to exit the loop.
Here's an updated version of your code with these issues fixed:
import random
def guess(word1, word2):
word1 = list(word1)
word2 = ''.join(word1.copy())
random.shuffle(word1)
word1 = ''.join(word1)
return word1, word2
while True:
word1, word2 = guess()
print('打乱后的顺序为:' + word1)
word3 = input('请猜单词:')
if word2 == word3:
print('恭喜你猜对了')
break
else:
print('不好意思猜错了')
Note: This code will keep generating new words to guess after each incorrect guess. If you want to keep the same word until it is guessed correctly, you can move the line word1, word2 = guess() outside of the while loop.
原文地址: https://www.cveoy.top/t/topic/pf0l 著作权归作者所有。请勿转载和采集!