-
-
Save Denenberg/316fc550a1dd1e8752cf756a560bb4ca to your computer and use it in GitHub Desktop.
This game generates a random mathematical quiz, asks the user to solve it, and checks if the answer is correct. The user has unlimited attempts to solve the quiz. If the answer is correct, the user passes the quiz, otherwise the user fails.
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 mathematical quiz, | |
# asks the user to solve it, and checks if the answer | |
# is correct. The user has unlimited attempts to solve | |
# the quiz. If the answer is correct, the user passes | |
# the quiz, otherwise the user fails. | |
import random | |
def generate_quiz(): | |
# generate two random numbers | |
num1 = random.randint(1, 10) | |
num2 = random.randint(1, 10) | |
# choose a random operator | |
operations = ["+", "-", "*", "/"] | |
op = random.choice(operations) | |
# perform the calculation | |
if op == "+": | |
result = num1 + num2 | |
elif op == "-": | |
result = num1 - num2 | |
elif op == "*": | |
result = num1 * num2 | |
else: | |
result = num1 / num2 | |
# return the quiz in the form of a tuple (question, answer) | |
return (f"{num1} {op} {num2}", result) | |
def play_quiz(quiz): | |
# ask the user to solve the quiz | |
question, answer = quiz | |
user_answer = float(input(f"What is the answer to {question}: ")) | |
# check if the user's answer is correct | |
if user_answer == answer: | |
print("Correct!") | |
return True | |
else: | |
print("Incorrect.") | |
return False | |
def run_quiz(): | |
# welcome message | |
print("Welcome to the Math Quiz!") | |
# generate a random quiz | |
quiz = generate_quiz() | |
# play the quiz | |
result = play_quiz(quiz) | |
# show the result | |
if result: | |
print("Congratulations, you passed the quiz!") | |
else: | |
print("Sorry, you failed the quiz.") | |
run_quiz() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment