Skip to content

Update math_game.py #382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 43 additions & 33 deletions Math_Game/math_game.py
Original file line number Diff line number Diff line change
@@ -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()