如何在此代码中添加用户输入?

时间:2017-11-23 09:48:08

标签: python python-3.x

我想知道如何在此代码中添加用户输入,以便用户可以选择主题(将添加更多主题)和难度,而不是必须在底部调用。任何解释都非常受欢迎,因为我对用户输入很不满意。

from collections import namedtuple
Question = namedtuple("Question", "question answer choices correct")

maths_questions = [Question("What is 1 + 1", "1 + 1 is 2", ["1", "2", "3", "4"], {"b", "2"}),
           Question("What is 2 + 3", "2 + 3 is 5", ["5", "4", "2", "1"], {"a", "5"})]

ansdict=[]

def quiz(questions, difficulty):
    score = 0
    for question in questions:
        global ansdict; ansdict = question.choices
        print(question.question)  
        output(difficulty, ansdict)
        users_answer = input().lower()
        if users_answer in question.correct:
            print("Correct")
            score += 1
        else:
            print("Incorrect", question.answer)  
    print("{} out of {}".format(score, len(questions)))


def output(difficulty, dicti):
    for i in range(difficulty):
        print(dicti[i])

quiz(maths_questions, 4)

2 个答案:

答案 0 :(得分:0)

要在代码中添加输入,请使用

等格式

(变量)=输入("(此处输入文字)")

我以后可以提供更好的例子。

答案 1 :(得分:0)

getdifficulty= input("How hard?")
quiz(maths_questions, getdifficulty)

这在此进一步说明:https://www.python-course.eu/python3_input.php