diff --git a/Math_Game/math_game.py b/Math_Game/math_game.py index 7e863ecf..3874e81f 100644 --- a/Math_Game/math_game.py +++ b/Math_Game/math_game.py @@ -1,51 +1,61 @@ import random import operator +import math -def errorHandle(problem_answer): - switch = False - validated_guess = 0.0 - while switch == False: +def get_user_input(prompt): + """Get a validated float input from the user.""" + while True: try: - validated_guess = float(input('Please enter a valid answer: ')) - if type(validated_guess) is float: - switch = True - break + return float(input(prompt)) except ValueError: - pass - return validated_guess + print("Invalid input. Please enter a number.") -def random_problem(): - operators = { - '+': operator.add, - '-': operator.sub, - '*': operator.mul, - '/': operator.truediv, +def generate_random_problem(): + """Generate a random math problem and return its answer.""" + operations = { + '+': operator.add, + '-': operator.sub, + '*': operator.mul, + '/': operator.truediv, } - num_1 = random.randint(1, 10) - num_2 = random.randint(1, 10) - operation = random.choice(list(operators.keys())) - answer = float(round(operators.get(operation)(num_1, num_2),3)) - print(f'What is {num_1} {operation} {num_2}') + num1 = random.randint(1, 10) + num2 = random.randint(1, 10) + op_symbol = random.choice(list(operations.keys())) + + # Avoid divide by zero + if op_symbol == '/': + while num2 == 0: + num2 = random.randint(1, 10) + + answer = round(operations[op_symbol](num1, num2), 3) + print(f"\nWhat is {num1} {op_symbol} {num2}?") return answer def ask_question(): - answer = random_problem() - try: - guess = float(input('Enter you answer: ')) - except ValueError: - guess = errorHandle(answer) - return guess == answer + """Ask one question and check the user's answer.""" + correct_answer = generate_random_problem() + user_answer = get_user_input("Enter your answer: ") + + # Use math.isclose to compare floats with a tolerance + if math.isclose(user_answer, correct_answer, rel_tol=1e-2): + return True + else: + print(f"Incorrect. The correct answer was: {correct_answer}") + return False -def game(): +def play_game(): + """Main game loop.""" score = 0 + print("🧠 Welcome to the Math Quiz Game!") while True: - if ask_question() == True: + if ask_question(): score += 1 - print('Correct !') + print("āœ… Correct!") else: - print('Incorrect') break - print(f'======== Game Over ========\nYou score is {score}\nKeep going!') + print(f"\nšŸŽ® Game Over! Your score: {score}") + print("Thanks for playing!") -game() +if __name__ == "__main__": + play_game()