python 在定义的函数中保持得分并 return 它

python keeping score in definded function and return it

所以我想做一个测验,你可以选择不同的类别。一切正常,但我无法使评分功能正常工作。如果我在三个正确答案后打印(分数)(分数应该是 3),它仍然是 0。 如果我将 return 分数放在分数 += 1 之后,它会在一个正确答案后自动停止,但我希望能够给出 3 个正确答案。

下面是部分代码

   def quizquestion(score,question_category):
       for question_number,question in enumerate(question_category): 
           print ("Question",question_number+1)
           time.sleep(1)
           slow_type (question)
           for options in question_category[question][:-1]: 
               slow_type (options)

           user_choice = input("make your choice: ")
           if user_choice == question_category[question][-1]: 
               replay = good[random.randint(0,7)]
               slow_type (replay)
               score += 1
           else: 
               replay = wrong[random.randint(0,7)]
               slow_type (replay)
               slow_type ("The correct answer should have been")
               print(question_category[question][-1])
               time.sleep(1)

       slow_type("okay you finished this category, lets see what your score is in this category")
       slow_type("You have"), print(score), slow_type("correct answer(s)")
       return score

类别之一:

 questions_random = {
     "How tall is the Eiffel Tower?":['a. 350m', 'b. 342m', 'c. 324m', 'd. 1000ft','a'],
     "How loud is a sonic boom?":['a. 160dB', 'b. 175dB', 'c. 157dB', 'd. 213dB', 'd'],
     "What is the highest mountain in the world?":['a. Mont Blanc', 'b. K2', 'c. Mount Everest', 'd. Mount Kilomonjaro', 'c']
 } 

如果您需要更多代码来帮助我,请告诉我

分数可以是关键字参数。这样它就有一个默认的初始值。这是从您的代码派生的工作示例。

注意:出于测试目的,我将 slow_type 替换为 print,将 good[random.randint(0,7)] 替换为 "\ncorrect",将 wrong[random.randint(0,7)] 替换为 "\nwrong\n"。 这行得通,返回了正确的分数。

您可以将上一轮题目的分数传入如下:

quizquestion(question_category, score=<current_score>).

您可以了解有关关键字参数的更多信息here

def quizquestion(question_category, score=0):
    boundary = "*************************************************"
    for question_number,question in enumerate(question_category): 
        print ("\nQuestion",question_number+1)
        time.sleep(1)
        print(question)
        for options in question_category[question][:-1]: 
            print(options)

    user_choice = input("make your choice: ")
    if user_choice == question_category[question][-1]: 
        replay = "\ncorrect!"
        print(replay)
        score += 1
        print(boundary)
    else: 
        replay = "\nwrong\n"
        print(replay)
        print("The correct answer should have been")
        print(question_category[question][-1])
        print(boundary)
        time.sleep(1)

    print("\nokay you finished this category, lets see what your score is in this category")
    print("You have {} correct answers!".format(score))
return score