【问题标题】:Menu python extracting an element from the array菜单python从数组中提取元素
【发布时间】:2014-03-27 17:47:39
【问题描述】:

我正在学习 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]

不多,我知道,但我真的不知道如何完成它。 有人可以帮我吗?

【问题讨论】:

    标签: python arrays menu extract


    【解决方案1】:

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

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

    你的while 循环会抛出一个错误,但是,如果用户选择了超出可用范围(包括 4)的东西,因为直到块结束才对其进行评估。你会想要做这样的事情而不是:

    if menu_item > len(questions):
        break
    

    另外,一些样式指针:

    TrueFalse 已在 python 中定义,因此您无需自己执行此操作,您的第一个 while 循环最好使用 for as

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

    【讨论】:

    • err,感谢您的回答,但事实是我没有找到必须添加“questions = get_questions()”和“question, answer = questions[menu_item]”行的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    相关资源
    最近更新 更多