Skip to main content
 首页 » 编程设计

python之如何将用户输入的字符串存储在变量中,然后查看这些输入是否包含在单词中

2024年12月31日21youxin

我正在尝试制作刽子手游戏。目前我仍在尝试弄清楚如何将用户输入的字符串存储在变量中。

我需要这个,因为如果用户在十次猜测之前就猜到了这个词,它会不断要求他们再输入一个字母。 我尝试创建一个变量,然后在用户输入更多字母时更新该变量。然而,如果用户没有以正确的顺序输入所有字母,那么这将不起作用,程序显然不会将其识别为正确的单词。

基本上我需要一种方法来存储输入的字符串(一次一个字母)并能够检查是否所有这些字母都包含在五个字母的单词中。

import random 
print("Welcome to hangman, guess the five letter word") 
words =["china", "ducks", "glass"] 
correct_word = (random.choice(words)) 
 
 
trials = 10 
 
for trial in range(trials): 
    guess = input(str("Enter Character:")) 
 
    if (len(guess) > 1): 
        print("You are not allowed to enter more than one character at a time") 
        continue 
    if guess in correct_word: 
        print("Well done " + guess + " is in the list!") 
    else: 
        print("Sorry " + guess + " is not included") 

请您参考如下方法:

好像是set正是您所需要的。

你从一个空的 set() 和 add 开始每次都是这封信。要检查字母是否足够,请使用 saved_set == set(correct_word)。