如果用户输入的索引号在问题列表中不存在,则显示“无效索引号”消息

2024-09-28 05:21:35 发布

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

我是新来的编程。请因为我不习惯stackoverflow,所以对写作中的任何错误深表歉意。 我想知道如果用户输入了一个列表中不存在的无效索引号,如何显示“无效索引号”消息。 下面是代码和函数,它被调用来提示用户输入一个输入(从0到n的整数),如果在列表中找到,它将显示问题和答案。在

def inputInt(prompt):
choice=raw_input(prompt)
return choice

if choice=="v":
        if not questions:
            print "No Questions Saved"
        else:
            print "Which Question number do you want to view?"
            selectedc=inputInt(">")    
            print questions[selectedc]['question']
            print questions[selectedc]['answer']+"(Correct)"
            print questions[selectedc]['wrong1']+"(Incorrect)"
            print questions[selectedc]['wrong2']+"(Incorrect)"
            print questions[selectedc]['wrong3']+"(Incorrect)"

我正在写一个程序来添加和查看问题及其答案。我列了一个“问题”清单。列表中的每一个条目都是一个由5个条目组成的字典,它们的关键字是“问题”、“答案”、“错误1”、“错误2”和“错误3”。在

请告诉我如果列表中没有特定的索引,我可以在控制台上显示消息的代码或方式。在

谢谢大家:)


Tags: 答案代码用户消息列表if错误条目
2条回答

听起来你想检查索引是否有效。一种简单的方法是检查索引是>=0还是{}

例如:

if selectedc >= 0 and selectedc < len(questions):
    print(questions[selectedc]['question'])
    ...
else:
    print('Invalid index number')

这适用于列表(您说过questions是),而如果您想为您的字典做类似的事情,kingradic的答案是有效的。在

{cds>集合中的{s}类型和类型都是有效的,{cds>在集合中可以使用一个有效的^操作符来检查这些类型。在

举个例子:

selectedc = inputInt(">")
if selectedc in questions:
    print(questions[selectedc]['question']
    ...

else:
    print("Question not found")
    ...

如果我理解问题的话,我应该这么做。在

相关问题 更多 >

    热门问题