So I need to make a calculator that converts strings into floats then calculate. The problem is I need to make error messages whenever:
- the user enters a string that does not contain operands and/or an operator.
- the user does not enter anything (the user simply pressed the Enter key).
- the user only enters an operand.
- the user only enters an operator.
- the user enters two operands.
- the user enters an operand and an operator.
- the user is trying to divide a number by 0.
- the user did not put a space in between the operands and the operator.
This is how the code looks like without error messages
# Interface
print ("Equation Calculator")
print (" ")
print ("My Equation Calculator is able to")
print (" Add: +")
print (" Subtract: -")
print (" Multiply: *")
print (" Divide: /")
print (" ")
print ("The equation you enter must follow this syntax:")
print (" <openrand><speace><operator><space><operand>.")
print ("An <operand> is any float number.")
print ("An <operator> is any is any of the operators mentioned above.")
print ("A <space> is an empty space.")
# Enter the equation
equation = input ("Enter your equation: ")
# Split the equation into Operand 1,2 and Operator
operand1,operator,operand2 = equation.split(" ")
# Show the user the equation
print ("Here is the equation you have entered: " + equation)
# Addition, Converting strings (operand 1 and 2) into float
if (operator == "+"):
answer = float(operand1) + float(operand2)
# Subtraction, Converting strings (operand 1 and 2) into float
if (operator == "-"):
answer = float(operand1) - float(operand2)
# Multiplication, Converting strings (operand 1 and 2) into float
if (operator == "*"):
answer = float(operand1) * float(operand2)
# DIvision, Converting strings (operand 1 and 2) into float
if (operator == "/"):
answer = float(operand1) / float(operand2)
# Display the answer
print ("The answer is: ",answer )
So for 7 and 8th errors I did this
# Error for not having a space
if (equation.find(" ") == False):
print ("Error #1: Please check if there is a space in between the two operands and the operator.")
# Error for dividing by 0
if (operand2 == "0"):
print ("Error #7: You cannot divide by 0.")
However python just bypasses this and still crashes. What is the problem with above code? How can I make it so the code prints error messages in above 8 situations? Also I cannot use the built-in functions eval( ) or exec(), break or continue or pass or sys.exit( ). I am very new to programming in general. Please help and thank you.
elsestatements - Julientry:operand1,operator,operand2 = equation.split("")except ValueError:to make sure you get 3 strings inequation. You can do a similar thing to catchValueErrorto make sure the operand strings can be converted to floats:try:operand1=float(operand1)except ValueError:. See Exceptions in the tutorial for details. - PM 2Ring