简体   繁体   中英

How to restart Python Code - Restarting a Math Quiz

I am working on a Math Quiz in Python and I want the python code for the math quiz to restart if the user says "Yes" to a restart question. Here's my python code. I am 7 so please take it easy:

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..")

You could call the actual math quiz under a wrapper function. This will allow you to continue to "play" based on user input.

Suggested code:

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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM