73 lines
2.7 KiB
Python
73 lines
2.7 KiB
Python
import random
|
|
from colorama import Fore, Style
|
|
|
|
|
|
def generate_arithmetic_question(max_digits=2, num_terms=2, operation=None):
|
|
"""
|
|
Generates an arithmetic question based on the configured digits, number of terms, and operation.
|
|
Ensures all results are positive.
|
|
"""
|
|
if operation is None:
|
|
operation = random.choice(["add", "sub"]) # Randomly choose addition or subtraction
|
|
|
|
terms = [random.randint(10 ** (max_digits - 1), 10 ** max_digits - 1) for _ in range(num_terms)]
|
|
|
|
if operation == "add":
|
|
question = " + ".join(map(str, terms))
|
|
correct_answer = sum(terms)
|
|
elif operation == "sub":
|
|
terms.sort(reverse=True) # Ensure subtraction produces a positive result
|
|
question = " - ".join(map(str, terms))
|
|
correct_answer = terms[0]
|
|
for term in terms[1:]:
|
|
correct_answer -= term
|
|
|
|
return f"{question} =", correct_answer
|
|
|
|
|
|
def quiz(max_digits=2, num_terms=2, operation=None):
|
|
"""
|
|
Arithmetic practice quiz.
|
|
Configurables:
|
|
- max_digits: Maximum digits for each term in the problem.
|
|
- num_terms: Number of terms in the arithmetic problem.
|
|
- operation: 'add', 'sub', or None for random.
|
|
"""
|
|
print(f"Welcome to the Arithmetic Practice Quiz!")
|
|
total_questions = int(input("How many questions would you like to solve? "))
|
|
print(f"Operation mode: {operation.upper() if operation else 'RANDOM'}")
|
|
correct_count = 0
|
|
|
|
for question_num in range(1, total_questions + 1):
|
|
question, correct_answer = generate_arithmetic_question(max_digits, num_terms, operation)
|
|
print(f"Question {question_num}/{total_questions}: {question}")
|
|
|
|
attempt = 0
|
|
while attempt < 2:
|
|
try:
|
|
user_answer = int(input("Your answer: "))
|
|
if user_answer == correct_answer:
|
|
print(Fore.GREEN + "Correct!" + Style.RESET_ALL)
|
|
correct_count += 1
|
|
break
|
|
else:
|
|
attempt += 1
|
|
if attempt < 2:
|
|
print(Fore.YELLOW + "Wrong! Try again." + Style.RESET_ALL)
|
|
else:
|
|
print(Fore.RED + f"Wrong! The correct answer is {correct_answer}" + Style.RESET_ALL)
|
|
except ValueError:
|
|
print(Fore.RED + "Please enter a valid number." + Style.RESET_ALL)
|
|
|
|
print(f"\nYou got {correct_count}/{total_questions} correct. Thanks for playing!")
|
|
|
|
|
|
# Run the quiz
|
|
if __name__ == "__main__":
|
|
# Adjust default parameters if needed
|
|
quiz(
|
|
max_digits=2, # Max digits per term
|
|
num_terms=2, # Number of terms in the problem
|
|
operation=None # Operation: 'add', 'sub', or None for random
|
|
)
|