【问题标题】:How can I check if user input is in a random string from a list?如何检查用户输入是否在列表中的随机字符串中?
【发布时间】:2020-10-09 20:05:08
【问题描述】:

我正在尝试编写刽子手。我很新,想知道一些事情。我已经想通了

 x = "Hello World"
print(x[2])
print(x[6])
print(x[10])

输出是

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")

我得到的错误信息是数字必须是整数。如果我尝试以不同的方式编写它,我有两个选择。

#the first option is :
j = int(input ())
#the second option is:
if j == chosen[0,int(nr_of_letters)]:

它们都不起作用。请问我怎么写正确。

【问题讨论】:

  • 试试:chosen = list[random.randint(0,3)]

标签: python list variables random input


【解决方案1】:

首先,从列表中选择一个随机单词:

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")

这样好吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多