CNSA-266-Personal/MathPractice.py

130 lines
3.5 KiB
Python
Raw Normal View History

2024-04-23 09:40:13 -04:00
import sys
import time
DEBUG = False
totalCorrect = 0
totalIncorrect = 0
# will ask the user if they want to exit the program
def tryExit():
userIn = ""
while True:
userIn = input("Would you like to exit the program? (y/n) ")
if userIn == "y" or userIn == "Y":
print("\n\n\nThank you for using Math Practice!")
time.sleep(0.5)
print("You got " + str(totalCorrect) + " correct, and " + str(totalIncorrect) + " incorrect.")
sys.exit(0)
elif userIn == "n" or userIn == "N":
break
print("Please enter y or n.")
time.sleep(0.2)
# loops forever until the user enters a valid input (float)
def getInput(message):
userInput = ""
while True:
userInput = input(message)
try:
userInput = float(userInput)
break
except Exception as e:
print("Please enter a valid number.")
time.sleep(0.2)
if userInput == -99:
tryExit()
return userInput
# loops forever until the user enters a valid operator
def getOperator():
userInput = ""
while True:
try:
userInput = input("Please choose an operator ( + - / * ): ")
if userInput == "+":
break
elif userInput == "-":
break
elif userInput == "*":
break
elif userInput == "/":
break
elif userInput == "-99":
tryExit()
else:
raise Exception("Please enter a valid operator.")
except Exception as e:
print(e)
time.sleep(0.2)
return userInput
# runs a calculation based on two numbers, and the operator provided
def calculate(first, second, op):
if op == "+":
return first + second
if op == "-":
return first - second
if op == "*":
return first * second
if op == "/":
return first / second
# returns the int value of a float if possible
def reduce(num):
oNum = num
intNum = int(num)
if intNum == oNum:
return intNum
else:
return oNum
if not DEBUG:
print("\n"*100)
print("Welcome to Math Practice!")
time.sleep(2)
print("This program will ask you to enter one number, then an operation, and a second number")
time.sleep(2)
print("You will then input the answer that you believe to be correct")
time.sleep(2)
print("Your score will be calculated based on how many you got correct and how many you guessed incorrectly")
time.sleep(2)
print("You may enter -99 to exit at any time")
time.sleep(2)
print("Enjoy!")
time.sleep(2)
input("Press Enter to start!")
print("\n"*100)
# The Main Running Space
while True:
num1 = getInput("Please enter the first number: ")
op = getOperator()
num2 = getInput("Please enter the second number: ")
print("\n")
print("Your equation is: " + str(reduce(num1)) + " " + op + " " + str(reduce(num2)))
userAnswer = getInput("Please enter what you think the answer is: ")
answer = calculate(num1, num2, op)
if float(userAnswer) == answer:
print("Correct!")
totalCorrect += 1
time.sleep(1)
print("\n"*100)
print("You may enter -99 to exit at any time\n")
else:
print("Incorrect. Better luck next time!.")
totalIncorrect += 1
time.sleep(1)
print("\n"*100)
print("You may enter -99 to exit at any time\n")