While writing this code I want that output must be independent of space used in input (eg. 2*3 should give 6 and 2 * 3 also gives the output 6). the code I am sharing is working fine with integer input but when I use float input it is giving error as:
Enter the calculation (Eg: 2 * 3): 4.7 * 5 Traceback (most recent call last): File "C:/Users/esjvaro/PycharmProjects/Python/condition.py", line 4, in num_1, operator, num_2 = input("Enter the calculation (Eg: 2 * 3): ").replace(" ","") ValueError: too many values to unpack (expected 3)
My Code:
i=1 while(i>0):
num_1, operator, num_2 = input("Enter the calculation (Eg: 2 * 3): ").replace(" ","")
num_1 = float(num_1)
num_2 = float(num_2)
if operator == "+":
print("{} + {} = {}".format(num_1, num_2, num_1 + num_2))
elif operator == "-":
print("{} - {} = {}".format(num_1, num_2, num_1 - num_2))
elif operator == "*":
print("{} * {} = {}".format(num_1, num_2, num_1 * num_2))
elif operator == "/":
print("{} / {} = {}".format(num_1, num_2, num_1 / num_2))
else:
print("Use + - * or / for calculation")
But if I use split() function in place of replace(" ","") then calculator is working fine with both integer and float input but this time it is dependent on space (eg. eg. 2*3 shows error and 2 * 3 gives the output 6). this time error is:
Enter the calculation (Eg: 2 * 3): 2*3 Traceback (most recent call last): File "C:/Users/esjvaro/PycharmProjects/Python/condition.py", line 4, in num_1, operator, num_2 = input("Enter the calculation (Eg: 2 * 3): ").split() ValueError: not enough values to unpack (expected 3, got 1)
Please help me out and tell how to prepare a calculator which works good in both the case whether input is integer or float, it must give the output with and without space.