菜单python从数组中提取元素

时间:2014-03-27 17:47:40

标签: python arrays menu extract

我正在从Josh Cogliati教程中学习,我来this page。 我已经编写了 test.py 示例,现在我正在尝试编写相同的练习,添加一个简单的菜单来提取列表的元素。 我怎么能这样做?

以下是代码:

true = 1
false = 0

def get_questions():
    return [["What color is the daytime sky on a clear day?","blue"],\
            ["What is the answer to life, the universe and everything?","42"],\
            ["What is a three letter word for mouse trap?","cat"]]

def check_question(question_and_answer):
    question = question_and_answer[0]
    answer = question_and_answer[1]
    given_answer = raw_input(question)
    if answer == given_answer:
        print "Correct"
        return true
    else:
        print "Incorrect, correct was:",answer
        return false
def run_test(questions):
    if len(questions) == 0:
        print "No questions were given."
        return
    index = 0
    right = 0
    while index < len(questions):
        if check_question(questions[index]):
            right = right + 1
        index = index + 1
    print "You got ",right*100/len(questions),"% right out of",len(questions)

run_test(get_questions())

到目前为止,这就是我的目标:

index = 0
menu_item = 0
while menu_item != 4:
print "-------------------"
print "1. Choose question n.1"
print "2. Choose question n.2"
print "3. Choose question n.3"
print "4. Exit"
menu_item = input("Pick an item from the menu: ")
if menu_item == 1:
    question = question_and_answer[0]
    answer = question_and_answer[1]

不是那么多,我知道,但我真的不知道如何完成它。 有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

好吧,你已经知道如何对列表进行切片,并且用户在你的问题列表中为你提供了第N个问题的选择,所以只需将其切片:

questions = get_questions()
question, answer = questions[menu_item]

但是,如果用户选择了可用范围之外的某些内容(包括4),则while循环将引发错误,因为直到块结束才会对其进行求值。你会想要做这样的事情:

if menu_item > len(questions):
    break

另外,一些风格指针:

TrueFalse已在python中定义,因此您无需自行执行此操作,并且while可以更好地为您的第一个for循环提供服务如

 for question in questions:
     if check_question(question):
         right += 1