声明不会打印

时间:2019-09-08 19:59:45

标签: python

在给出正确的答案时会打印声明,但在给出错误的答案时不会打印。

QUESTIONS = ["2 + 2", "10 // 5", "8 == 2 ** 3", "5 % 2 == 0"]
ANSWERS = ["4", "2", "True", "False"]


def main():
    count=0
    question=0
    for i in QUESTIONS:
        print(i)
        z=input("enter your answer:")
        for x in range(len(QUESTIONS)):
            if z == ANSWERS[x]:
                print("Your answer is correct. Good job!")
                count=count+1
                question=question+1
                if z!=ANSWERS[x]:
                    print("Your answer is wrong")
                    question = question+1
        if z == "quit":
            break  
    print("You have"+ " "+ str(count) + " " + "points.") 
    print(("You have answered " + str(question)) + " " + "correctly out of 4.") 
main()

当给出错误答案时,如何获取它以打印语句。另外,如何在末尾加上百分比,以告诉我有多少正确答案(正确答案的比例)。  enter image description here

2 个答案:

答案 0 :(得分:1)

我的代码有两个主要问题:

1。)您的代码将显示“您的答案正确。做得好!”如果我输入任何可能的答案,无论当前问题是什么。例如,如果问题是“ 2 + 2”,而我输入“ 2”,则您的代码将说出此答案是正确的。这是由于您的for x in range(len(QUESTIONS))循环所致。它将用户的输入与所有答案进行比较,如果其中任何一个匹配,它都会很高兴。

2。)打印“您的答案是错误的”的代码永远无法到达,也永远不会执行。这是由于您已将一个if语句嵌套在另一个if语句中。

def main():
    questions = [
        "What is 2 + 2?",
        "What is 10 // 5?",
        "True or False: 8 == 2 ** 3",
        "True or False: 5 % 2 == 0"
    ]

    answers = [
        "4",
        "2",
        "True",
        "False"
    ]

    correctly_answered_count = 0

    for current_question, current_answer in zip(questions, answers):
        print(current_question)
        user_answer = input("Enter your answer: ")
        if user_answer == current_answer:
            print("Your answer is correct. Good job!")
            correctly_answered_count += 1
        else:
            print("Your answer is wrong.")
    print(f"You have answered {correctly_answered_count} correctly out of {len(questions)}.")

main()

输出:

What is 2 + 2?
Enter your answer: 2
Your answer is wrong.
What is 10 // 5?
Enter your answer: 2
Your answer is correct. Good job!
True or False: 8 == 2 ** 3
Enter your answer: True
Your answer is correct. Good job!
True or False: 5 % 2 == 0
Enter your answer: False
Your answer is correct. Good job!
You have answered 3 correctly out of 4.

答案 1 :(得分:0)

您没有缩进。第二个if中的第二个if在第二个for中的第一个if内部。您只能进入if,如果您的答案是正确的,则检查答案是否为假,因此基本上不会。

尝试一下:

for x in range(len(QUESTIONS)):
    if z == ANSWERS[x]:
        print("Your answer is correct. Good job!")
        count=count+1
        question=question+1
    if z!=ANSWERS[x]:
        print("Your answer is wrong")
        question = question+1