-
-
Save Denenberg/38a715612994ce6c439841df2a8101cf to your computer and use it in GitHub Desktop.
This game generates a random problem in the form of an equation like x + 5 = 12 and asks the user to solve for the variable. The user inputs their answer and the game checks if it's correct, printing a message accordingly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This game generates a random problem in the form of an | |
# equation like x + 5 = 12 and asks the user to solve for | |
# the variable. The user inputs their answer and the game | |
# checks if it's correct, printing a message accordingly. | |
import random | |
def generate_problem(): | |
operations = ['+', '-', '*', '/'] | |
operation = random.choice(operations) | |
x = random.randint(1, 10) | |
y = random.randint(1, 10) | |
variable = random.choice(['x', 'y', 'z']) | |
problem = f'{variable} {operation} {x} = {y}' | |
return problem, variable, y, x, operation | |
def solve_problem(problem, variable, y, x, operation): | |
if operation == '+': | |
return y - x | |
elif operation == '-': | |
return y + x | |
elif operation == '*': | |
return y / x | |
elif operation == '/': | |
return y * x | |
while True: | |
problem, variable, y, x, operation = generate_problem() | |
solution = solve_problem(problem, variable, y, x, operation) | |
answer = int(input(f'Solve for {variable}: {problem} ')) | |
if answer == solution: | |
print('Correct!') | |
else: | |
print(f'Incorrect. The answer is {solution}.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment