我正在用Python做一个数学测验,我想让Python的数学测验代码重新启动,如果用户对一个重新启动的问题说“是”。 下面是我的python代码。 我7岁,所以请放轻松:
from random import randint
class MathQuiz:
def whole_math_quiz(self):
num1 = randint(2, 9)
num2 = randint(3, 10)
product = num1 * num2
ans = int(input(f"What is {num1} X {num2}? "))
if ans == product:
print("Well done! You have got the answer right!")
print("P.S Run the python file again to play again..")
else:
print("You have got it wrong!")
print("P.S Run the python file again to play again..")
您可以在包装器函数下调用实际的数学测验。 这将允许你根据用户输入继续“玩”。
建议代码:
from random import randint
class MathQuiz:
def whole_math_quiz(self):
while True :
self.actual_math_quiz()
newgame = input ("Do you want to play again ?")
if newgame.lower() not in [ 'y', 'yes']:
break
def actual_math_quiz(self):
num1 = randint(2, 9)
num2 = randint(3, 10)
product = num1 * num2
ans = int(input(f"What is {num1} X {num2}? "))
if ans == product:
print("Well done! You have got the answer right!")
else:
print("You have got it wrong!")
您可以启动一个while循环,并在结束时请求重新启动。 我让它变得简单,只加了两个条件。 也许您想捕获不同的答案,然后使用elif扩展if语句。
if __name__ == "__main__":
quiztime = True
while quiztime:
quiz = Mathquiz()
quiz.whole_math_quiz()
restart = input("want to restart? (Yes/No)")
if restart == "Yes":
pass
else:
print("Seems like you dont want to play anymore.")
quiztime = False