我的quiz()方法不会更新其分数,我该如何解决这个问题?

时间:2016-01-29 22:57:45

标签: python python-2.7

我在编写python方面相对无能,作为一种练习方式我尝试编写一个基本程序来测验人。我最初是作为一个完全扩展的程序编写的,它工作得很好,所以我试着把它写成一个函数来大大减少我需要的代码量。这也很有效,但每次使用时得分值不会增加。代码和结果如下所示:

def quiz(question,answer, score):
    import time
    a = raw_input(question)
    if a.lower() == answer.lower():
        score = score + 1
        if score == 1:
            print("correct! So far your score is an awesome " + str(score) + "     point")
            time.sleep(0.5)
        else:
            print("correct! So far your score is an awesome " + str(score) + " points")
            time.sleep(0.5)
        return score
    else:
        print("wrong, dumbass! The correct answer was " + answer + "! So far your score is an abysmal " + str(score) + " points")
        time.sleep(0.5)
    actual_score = 0
    quiz("what is my favourite colour? ", "green", actual_score)
    quiz("What is my favourite game? ", "cards against humanity",    actual_score)
    quiz("Who's better: Gandalf or Dumbledore? ", "Gandalf", actual_score)

返回以下内容:

  

我最喜欢的颜色是什么?绿色   正确!到目前为止,你的得分是一个非常棒的1分   我最喜欢的游戏是什么?反人类的卡片   正确!到目前为止,你的得分是一个非常棒的1分   谁更好:甘道夫或邓布利多?甘道夫   正确!到目前为止,你的得分是一个很棒的1分

我真的不知道该怎么做才能解决这个问题,所以我很感激任何帮助!

3 个答案:

答案 0 :(得分:1)

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

  1. 您应该重置score功能
  2. 范围之外的quiz()
  3. 即使答案错误,您应该从score函数返回quiz() var
  4. 试试这个!

    def quiz(question,answer, score):
        import time
        a = raw_input(question)
        if a.lower() == answer.lower():
            score = score + 1
            if score == 1:
                print("correct! So far your score is an awesome " + str(score) + "     point")
                time.sleep(0.5)
            else:
                print("correct! So far your score is an awesome " + str(score) + " points")
                time.sleep(0.5)
        else:
            print("wrong, dumbass! The correct answer was " + answer + "! So far your score is an abysmal " + str(score) + " points")
            time.sleep(0.5)
    
        return score    
    
    
    actual_score = 0
    new_score = quiz("what is my favourite colour? ", "green", actual_score)
    new_score = quiz("What is my favourite game? ", "cards against humanity", new_score)
    new_score = quiz("Who's better: Gandalf or Dumbledore? ", "Gandalf", new_score)
    

答案 1 :(得分:0)

您无法在每个问题后保存返回的分数。您每次将原始0发送回测验。试着这样称呼:

actual_score = 0
actual_score = quiz("what is my favourite colour? ", "green", actual_score)
actual_score = quiz("What is my favourite game? ", "cards against humanity",    actual_score)
actual_score = quiz("Who's better: Gandalf or Dumbledore? ", "Gandalf", actual_score)

编码仍然达不到专业标准,但那是你领导的地方,而不是你现在需要的地方。保持良好的努力!

答案 2 :(得分:0)

这可以替代“tknickman”所说的,尽管仍然不是最好的方法。我会使用课程和单身人士。

{{1}}