用户输入的字母是否是 CPU 选择中的字母?



我试图检查用户输入是否是CPU所选单词中的一个字母。如果这是不可能的方式,请告诉我,谢谢。

import random
test_list = [ 'yes', 'no']
# guessing list
print("Original list is : " + str(test_list))
cpu_choice =[]
cpu_choice=("Random element is :", random.sample(test_list, 1)) 
print(cpu_choice) 
# i know it gives the answer i'm just using this to test and get the program to work 
userinput = input('guess a letter ')
for letter in userinput:
if letter in userinput == letter in cpu_choice:
print('correct')
elif print:
print('wrong')

我将它修改为循环通过cpu_choice而不是userinput (userinput只是一个字母)。

将结果的打印移出循环,以便程序不会对单词中每个不匹配的字母打印'wrong'。

userinput = input('guess a letter: ')[0]
match = False
for letter in cpu_choice[1][0]:
if letter == userinput:
match = True
break
if match:
print('correct')
else:
print('wrong')

letter in userinput正在计算该字母是否在用户的输入中,我们知道这是因为您正在循环userinput中的字母以获得letter。您应该删除if语句的这一部分,只留下if letter in cpu_choice:

然而,程序的其余部分看起来应该可以工作,尽管用户只有一次机会猜字母,因为您只获得一次输入。

最新更新