如何计算用户输入错误的次数

时间:2018-11-24 22:12:20

标签: python python-3.x

我正在做一个游戏,想要解决所有问题。如果用户回答错误,我想知道发生了多少次。

此代码有点问题。当我运行所有程序时,第一个和第二个函数正确运行。但是当我要打印x_errors时,它说“名称'answer'未定义”。我不明白,因为在我的代码中,“答案”是“ 10”,“ 20”和“ 30”。希望有人可以帮助我更好地理解这一点。我感谢所有帮助!

代码:

def question():
    input_question("How old are Ring?", "10")
    input_question("How old are King?", "20")
    input_question("How old are Bing?", "30")

def input_question(question, answer):
    print(question)
    user_answer = input("Your answer: ")
    wrong = 0
    while user_answer != answer:
        wrong = 1
        print("Try again")
        user_answer = input("Your answer: ")
    print("Correct!")
    return wrong

question()
x_errors = input_question(question, answer)
print(x_errors)

谢谢!

2 个答案:

答案 0 :(得分:1)

错误“未定义名称答案”来自此行:

x_errors = input_question(question, answer)

在调用函数时未定义变量答案。此外,问题将是一个代表您在代码开始时声明的问题Question()的对象,而不是字符串。

据我了解,由于您调用了问题()方法,该方法还用问题和期望的答案调用了3次input_question(),因此,无需像在结尾处那样调用input_question。您的文件。您的代码必须如下所示:

def question():
    x_errors = input_question("How old are Ring?", 10) #remove the quote on the answer
    print (x_errors)
    x_errors = input_question("How old are King?", 20)
    print (x_errors)
    x_errors = input_question("How old are Bing?", 30)
    print (x_errors)

def input_question(question, answer):
    print(question)
    user_answer = input("Your answer: ")
    wrong = 0
    while user_answer != answer:
        wrong+=1
        print("Try again")
        user_answer = input("Your answer: ")
    print("Correct!")
    return wrong

question()
#x_errors = input_question(question, answer)
#print(x_errors)

答案 1 :(得分:0)

您可以在input_question内部实现错误答案计数机制,并在question函数中保留错误答案的全局计数:

def question():
    questions = [
        ("How old are Ring?", "10"),
        ("How old are King?", "20"),
        ("How old are Bing?", "30"),
    ]
    global_wrong_count = 0
    for text, answer in questions:
        global_wrong_count += input_question(text, answer)
    return global_wrong_count


def input_question(question, answer):
    print(question)
    user_answer = input("Your answer: ")
    wrong_count = 0
    while user_answer != answer:
        wrong_count += 1
        print("Try again")
        user_answer = input("Your answer: ")
    print("Correct!")
    return wrong_count


print("User got it wrong {} time(s)".format(str(question())))