python中正确的答案跟踪器

时间:2017-09-19 20:55:59

标签: python

我一直试图找出如何为我制作的迷你测验添加分数计数器。我尝试了不同的东西,甚至试图查找如何做到这一点,但我无法弄清楚是什么原因。请帮忙!

这是代码:

tick()

2 个答案:

答案 0 :(得分:0)

您需要在函数中声明score为全局。

def question2():
    # declare that you're using the global variable score
    global score
    print("2.   Who was the last Tigers pitcher to throw a no-hitter?")
    b = input("What is your final answer:")

    if b == 'Justin Verlander':
        print('I am impressed whith how smart you are')
        score += 1
    else:
        print("Are you even trying")  
    return 

如果您没有告诉解释器您正在使用全局变量,那么它假定您指的是在函数范围内声明的score变量。

答案 1 :(得分:0)

作为Allie过滤器wrote,将score声明为全局是一种可能性。您还可以采用OOP启发方法,并创建class Test作为方法question,将score作为类变量。

class Test:
    score = 0

    def question1(self):
        print("1. Who hit the walk-off home run to extend the A's AL-record win streak to 20 games in 2002?"
          "A. Kevin Millar"
          "B. Scott Hatteberg"
          "C. Sammy Sosa"
          "D. Josh Donaldson")
        a = input("Please enter your answer in a lower case letter:")
        if a == 'C':
            print('You are smart!')
            self.score += 1 
        else:
            print('Better luck next time!') 
        return True

    def question2(self):
    ...
    ...

    def take_quiz(self):
        self.question1()
        self.question2()
        return self.score

您可以通过创建Test的实例并在其上调用方法take_quiz()来运行测试。

可以在heredocumentation中找到OOP的一些基础知识。