You're going to write an interactive calculator! User input is assumed to be a formula that consist of a number, an operator (at least + and -), and another number, separated by white space (e.g. 1 + 1). Split user input using str.split(), and check whether the resulting list is valid. If the input does not consist of 3 elements, raise a SyntaxError('invalid syntax'). Try to convert the first and third input to a float (like so: float_value = float(str_value)). Catch any ValueError that occurs. If the second input is not '+' or '-', again raise a SyntaxError('invalid syntax'). If the input is valid, perform the calculation and print out the result. The user is then prompted to provide new input, and so on, until the user enters quit. An interaction could look like this: >>> 1 + 1 2.0 >>> 3.2 - 1.5 1.7000000000000002 >>> quit
时间: 2023-11-28 17:51:18 浏览: 24
Here's the code for the interactive calculator:
```
while True:
user_input = input("Enter a formula (or 'quit' to exit): ")
if user_input == "quit":
break
formula = user_input.split()
if len(formula) != 3:
raise SyntaxError("invalid syntax")
try:
num1 = float(formula[0])
num2 = float(formula[2])
except ValueError:
raise SyntaxError("invalid syntax")
operator = formula[1]
if operator not in ["+", "-"]:
raise SyntaxError("invalid syntax")
if operator == "+":
result = num1 + num2
else:
result = num1 - num2
print(result)
```
This code uses a while loop to keep prompting the user for input until they enter 'quit'. It then splits the input into a list of three elements and checks whether the input is valid. If it is, it performs the calculation and prints the result. If not, it raises a SyntaxError.