在 Python 中不使用全局变量重写以下代码的替代方法是什么?

What is the alternative way to rewrite the below code without using global variables in Python?

有一个动物问答程序。该程序向玩家询问一些关于动物的问题。 他们有 3 次机会回答每个问题。每个正确答案都会 得一分。在测验结束时,程序会显示 玩家的最终得分。 代码在这里:

score = 0
def check_guess(guess, answer):
    global score
    still_guessing = True
    attempt = 0
    while still_guessing and attempt < 3:
        if guess.lower() == answer.lower():
            print('Correct answer')
            score = score + 1
            still_guessing = False
        else:
            attempt = attempt + 1
            
            if attempt < 3:
                guess = input('Sorry wrong answer. Try again. ')                    
    if attempt == 3:
        print('The correct answer is ' + answer)

print('Guess the Animal!')
guess1 = input('Which bear lives at the North Pole? ')
check_guess(guess1, 'polar bear')
guess2 = input('Which is the fastest land animal? ')
check_guess(guess2, 'cheetah')
guess3 = input('Which is the largest animal? ')
check_guess(guess3, 'blue whale')
print('Your score is ' + str(score))

我知道使用 'global' 变量不是一个好习惯。所以我用了另一种方法让它工作:将参数传递给函数。它看起来像这样:

score = 0
def check_guess(guess, answer, score):    
    still_guessing = True
    attempt = 0
    while still_guessing and attempt < 3:
        if guess.lower() == answer.lower():
            print('Correct answer')
            score = score + 1
            still_guessing = False
        else:
            attempt = attempt + 1
            
            if attempt < 3:
                guess = input('Sorry wrong answer. Try again. ')                    
    if attempt == 3:
        print('The correct answer is ' + answer)
    return score

print('Guess the Animal!')
guess1 = input('Which bear lives at the North Pole? ')
score1 = check_guess(guess1, 'polar bear', score)
guess2 = input('Which is the fastest land animal? ')
score2 = check_guess(guess2, 'cheetah', score1)
guess3 = input('Which is the largest animal? ')
score3 = check_guess(guess3, 'blue whale', score2)
print('Your score is ' + str(score3))

但我觉得我做的方式有点复杂。所以我只是想知道是否有更好的方法可以不使用 'global' 变量,或者在这种情况下,使用 'global' 变量是最好的解决方案?

函数实际上不需要与全局分数交互,您只需要它来确定一个问题的分数。我还简化了循环:

score = 0
def check_guess(guess, answer):
    for attempt in range(3):
        if guess.lower() == answer.lower():
            print('Correct answer')
            return 1
        guess = input('Sorry wrong answer. Try again. ')                    
    print('The correct answer is ' + answer)
    return 0

print('Guess the Animal!')
guess1 = input('Which bear lives at the North Pole? ')
score += check_guess(guess1, 'polar bear')
guess2 = input('Which is the fastest land animal? ')
score += check_guess(guess2, 'cheetah')
guess3 = input('Which is the largest animal? ')
score += check_guess(guess3, 'blue whale')
print('Your score is ' + str(score))

如果您希望降低复杂性,一种方法是从结构中抽象出内容。它的行数有点长,但更灵活,它封装了所有状态。

您可以制作一个简单的 Quiz class 来接受问题和答案并在内部跟踪测验的状态。这使您可以将其重复用于其他测验类型并更轻松地添加问题:

class Quiz:
    def __init__(self, subject, question_answers):
        '''Expects the quiz subject and a list of tuples of question / answer pairs'''
        self.score = 0
        self.subject = subject
        self.question_answers = question_answers
    
    def ask(self, question, answer, tries):
        '''Asks a question returning whether the answer was correct'''
        guess = input(question).lower()

        for i in range(tries - 1):
            if guess == answer:
                return True
            guess = input('Sorry wrong answer. Try again.')   

        return False
            
    def play(self):
        '''Starts the game, prints score at the end'''
        print(f'Guess the {self.subject}!')
        for q, a in question_answers:
            self.score += self.ask(q, a, 3)

        print(f'Your score is {self.score}')


questions = [
    ('Which bear lives at the North Pole? ', 'polar bear'),
    ('Which is the fastest land animal?', 'cheetah'),
    ('Which is the largest animal?', 'blue whale')
]

q = Quiz('Animal', questions)
q.play()