python将用户输入与列表进行比较,并附加到限制条目项的新列表中

2024-06-01 13:54:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用LPTHW学习python,并尝试构建自己的游戏作为练习36。我希望用户从10个规程集中输入一个特定的字符串。我可以将输入与定义的列表进行比较,但是我不能将用户限制在5个条目之内。相反,我可以限制用户只有五个输入,但不能同时进行这两个输入。在

我创建了规程列表(最初是字符串名称

discipline_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

然后我创建了一个空列表

^{pr2}$

下面的代码用于比较用户输入与规程列表,并将用户输入附加到新的空列表(来自其他答案的代码)。在

while True:
    d = raw_input("enter your choice of discipline >> ")
    d = str(d)

    found_d = False
    for i in discipline_list:
        if d == i:
            found_d = True

    if found_d:
        your_disciplines.append(d)
    else:
        print("Incorrect entry")

我可以使用for循环来限制用户条目,但不能将其与比较结合起来。我所有的尝试都超过了五次。在

for d in range(0, 5):

任何帮助都将不胜感激。在


Tags: 字符串代码用户intrue列表foryour
2条回答

如果要使用while循环,可以尝试:

num = input("Enter your disciplines number >> ")  # This is not required if you want to fix num to 5
j = 0

while j < int(num):
    d = raw_input("enter your choice of discipline >> ")
    d = str(d)

    found_d = False
    for i in discipline_list:
        if d == i:
            found_d = True

    if found_d:
        your_disciplines.append(d)
    else:
        print("Incorrect entry")
    j += 1

一些注意事项:

而不是:

^{pr2}$

您可以:

if d in discipline_list:
    found_d = True

另外,您不需要使用found_d变量。在

简化代码可以是:

num = input("Enter your disciplines number >> ")
i = 0

while i < int(num):
    d = raw_input("enter your choice of discipline >> ")
    d = str(d)

    if d in discipline_list:
        your_disciplines.append(d)
    else:
        print("Incorrect entry")
    i += 1

要组合这两个条件,请检查your_disciplines的长度作为while循环条件,只有当有5时才退出。在

while len(your_disciplines) < 5:
    d = raw_input("enter your choice of discipline >> ")
    d = str(d)

    if d not in your_disciplines:
        your_disciplines.append(d)
    else:
        print("Incorrect entry")

相关问题 更多 >