1 | initial version |
There are many ways to design a simple calculator that includes the operators of addition, subtraction, multiplication, and division, while also utilizing the "IsDigit" function to identify whether the input is a numeric value or not. Here is one possible design in Python code:
# Define a function that checks if a string is a numeric value
def is_numeric(s):
try:
float(s)
return True
except ValueError:
return False
# Initialize variables for input and calculation
expr = ""
result = None
# Loop to get user input and perform calculations
while True:
# Get user input
inp = input("> ")
# If input is a digit, append it to the expression
if is_numeric(inp):
expr += inp
# If input is an operator, evaluate the expression so far and update the result
elif inp in "+-*/":
if result is None:
# If there is no previous result, set it to the current expression
result = float(expr)
else:
# Otherwise, evaluate the previous result with the current expression and operator
if inp == "+":
result += float(expr)
elif inp == "-":
result -= float(expr)
elif inp == "*":
result *= float(expr)
elif inp == "/":
result /= float(expr)
# Reset the expression for the next input
expr = ""
# If input is "q", quit the program
elif inp == "q":
break
# If input is invalid, print an error message
else:
print("Invalid input")
# Print the current result
print(result)
This code defines a function is_numeric
that returns True
if a string can be converted to a float
and False
otherwise. The expr
variable stores the current expression being entered by the user, and the result
variable stores the current result of the calculation. The program loops indefinitely to get user input and perform calculations.
If the input is a digit, it is appended to the expr
variable. If the input is an operator (+
, -
, *
, or /
), the current expression is evaluated with the previous result (if any) using the operator, and the result
variable is updated accordingly. The expr
variable is reset for the next input.
If the input is "q", the program quits. If the input is invalid (i.e., not a digit, operator, or "q"), an error message is printed. The current result
variable is printed after each input.