gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:47 26 4
gpt4 key购买 nike

我在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)

这将返回以下内容:

what is my favourite colour? green correct! So far your score is an awesome 1 point What is my favourite game? cards against humanity correct! So far your score is an awesome 1 point Who's better: Gandalf or Dumbledore? gandalf correct! So far your score is an awesome 1 point

我真的不知道该怎么做才能解决这个问题,因此我将不胜感激任何帮助!

最佳答案

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

  1. 您应该在 quiz() 函数范围之外重置分数
  2. 即使答案错误,您也应该从 quiz() 函数返回 score var

试试这个!

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)

关于python - 我的 quiz() 方法不会更新其分数,我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35095599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com