-1

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.

  • If you need to split it so that you have the operator and the operand either side, regardless of space, you probably want to use a regular expression. – khelwood Jun 28 '20 at 15:12

1 Answers1

0

If you need to split it so that you have the operator and the operand either side, regardless of space, you could use a regular expression.

Here is how you might do that simply:

import re

... 

line = input('Enter the calculation:')
m = re.match(r'\s*(-?[0-9.]+)\s*([+/*-])\s*(-?[0-9.]+)\s*', line)
num_1,operator,num_2 = m.groups()

...

You'll get an exception from this if your input doesn't match the expected pattern.

Regular expressions are explained at Reference - What does this regex mean?

khelwood
  • 55,782
  • 14
  • 81
  • 108