Classes/Spring 2025/ENGR 490/4/A4/Scripts/math_quiz.py

84 lines
2.4 KiB
Python

# Import Modules
import random
import time
# Set the seed based on time
random.seed(time.time())
# Set Variables count and correct
count = 1
correct = 0
# Function that genrates a random equation and returns the answer with numbers from range x to y
def gen_function(x,y):
operand = gen_operand()
num1 = gen_number(x,y)
num2 = gen_number(x,y)
ans = gen_answer(operand, num1, num2)
return ans
# Displays the equation to the user and calculates and returns the answer
def gen_answer(operand, num1, num2):
match(operand):
case 1:
print(f"{num1} + {num2} = ?")
return num1 + num2
case 2:
print(f"{num1} - {num2} = ?")
return num1 - num2
case 3:
print(f"{num1} * {num2} = ?")
return num1 * num2
case 4:
print(f"{num1} / {num2} = ?")
return num1 / num2
case 5:
print(f"{num1} % {num2} = ?")
return num1 % num2
# Generates a random number 1 to 5 that corresponds to the operand
def gen_operand():
return random.randint(1,5)
# Generates a random number for range x to y
def gen_number(x,y):
return random.randint(x,y)
# Intro text
print("Welcome to the Math Quiz!\nAll questions use \033[94mints\033[0m so give your answer as an \033[94mint\033[0m!")
print("Type \033[91mexit\033[0m to exit the program")
# While loop that runs for 5 iterations generating a new equation each time keeping track of answers
while(count <= 5):
# Shows current question and generates a new function with answer
print(f"Question {count}:\n")
ans = gen_function(1,100)
# Takes user input for the answer
user_ans = input("Answer: ")
# Check if user wants to exit else makes input an int
if(user_ans.lower() == "exit"):
break
else:
user_ans = int(user_ans)
# If the answer equals what the user put correct goes up 1 else just increse count
if(user_ans == int(ans)):
print(f"\033[92mCorrect!\nGood Job!\033[0m\n")
count += 1
correct += 1
print(f"You have \033[96m{correct}\033[0m so far!\n")
else:
print(f"\033[31mWrong!\nCorrect Answer: {int(ans)}\nNext Question!\033[0m\n")
count += 1
print(f"You have \033[96m{correct}\033[0m so far!\n")
# Displays final message showing how many correct
print(f"You got \033[96m{correct}\033[0m out of {count} correct!\nThanks for Playing!")