[英]How can I check if user input is in a random string from a list?
我正在尝试对刽子手进行编程。 我很新,想知道一些事情。 我已经想通了
x = "Hello World"
print(x[2])
print(x[6])
print(x[10])
output 是
l
W
d
我想知道我是否可以这样写:
import random
list = ["Hi","Hello","Hi wrld","Hello world"]
chosen = list(random.randint(1,4)
nr_of_letters = len(chosen)
# j is the letter the user guesses
j = input()
if j == chosen[0,nr_of_letters]:
print("something")
else:
print("something else")
我得到的错误信息是该号码必须是 integer。如果我尝试以不同的方式编写它,我有 2 个选项。
#the first option is :
j = int(input ())
#the second option is:
if j == chosen[0,int(nr_of_letters)]:
他们都不工作。 请问我怎样才能正确地写那个。
所以首先,从列表中选择一个随机单词:
import random
words = ["Hi","Hello","Hi wrld","Hello world"]
chosen = random.choice(words)
# Chosen will now be one of the words in the list
由于您正在尝试编写 hangman 代码,我假设您知道您需要一个 while 循环来允许用户继续提供输入,所以我将只使用您在此处给出的内容作为示例。 因此,为了检查他们是否输入了正确的字母:
j = input()
if j in chosen:
print("something")
else:
print("something else")
那样行吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.