I'm trying to use this loop to condense existing code, but storing the operators in a list and then drawing from it doesn't work, it throws this error: TypeError: unsupported operand type(s) for +: 'float' and 'str'
I understand that it's not interpreting the operator
variable as an actual math operation, it's reading it as a str
, but I'm not sure how to fix that. Here's the complete loop I've built.
operators = ["+", "-", "*", "/", "^"]
for operator in operators:
math_expression = input("Enter your math expression, or (q)uit: ")
print("Operator found " + operator)
operator_position = math_expression.find(operator) # find operator
print("Found " + operator + "operator at index " + str(operator_position))
first_number = math_expression[:operator_position] # find first number
second_number = math_expression[operator_position + 1:] # find second number
answer = float(first_number) + operator + float(second_number)