# input a string str = input("Enter the expression: ") # make an array to check the operator opArr = ["+","-","*","/"] # check for operator op = "" for operator in opArr: if str.find(operator) == 1: op = operator # split the array splitStr = str.split(op) print(splitStr) # perform mathematical operations if op == "+": result = float(splitStr) + float(splitStr) elif op == "-": result = float(splitStr) - float(splitStr) elif op == "*": result = float(splitStr) * float(splitStr) elif op == "/": result = float(splitStr) / float(splitStr) else: result = "Something Went Wrong!!!" print(result)
Here Output is : Enter an expression: 5+5 // works output is 10
but when I enter 5.0+5 or any other decimal number it prints out an error.
Well, I can see the problem that split() method converts the string into a char array. Is there a way to convert it to a string array or any other way to hold an element like [“5.0”, “5”] like that so the output is 10.0 for 5.0+5?
From the docs:
Return the lowest index in the string where substring sub is found within the slice
s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return
-1if sub is not found.
The problem is that during
5.0+5, the operator
+ is present on the 3rd index position. But 3 is not equal to 1. So
op remains the same. And
split needs some separator on which it could split the string.
You can use
in operator here which returns
True if a specific substring is found in the main string.
for operator in opArr: if operator in str1: op = operator