As you already found out, split() parses the values in strings. So
For extra credit you could:
a. Check to make sure you have exactly 3 items in the expression
b. Assuming you are working with integers only, you could check that num1 and num2 are numbers (e.g. num1.isdigit()).
c. Checking for 'float' is probably beyond the scope of this exercise. The following working code is probably for future reference in combining float and int:
3 + 4
is really string concatenation and gives a result of 34
.For extra credit you could:
a. Check to make sure you have exactly 3 items in the expression
len(expression)
.b. Assuming you are working with integers only, you could check that num1 and num2 are numbers (e.g. num1.isdigit()).
c. Checking for 'float' is probably beyond the scope of this exercise. The following working code is probably for future reference in combining float and int:
def get_int_or_float(v): # NOTE: '1.0' will be identified as type 'int' try: number_as_float = float(v) number_as_int = int(number_as_float) if number_as_float == number_as_int: return number_as_int else : return number_as_float except: return v num1 = '1' num1 = get_int_or_float(num1) print(num1, type(num1)) num1 = '1a' num1 = get_int_or_float(num1) print(num1, type(num1)) num1 = '1.1' num1 = get_int_or_float(num1) print(num1, type(num1)) num2 = 3.3 if isinstance(num1, str) or isinstance(num2, str): # this would be the error branch print("string") else: # this would be the calculation branch - exactly as you have it print("int or float or combination of both")
Output:1 <class 'int'>
1a <class 'str'>
1.1 <class 'float'>
int or float or combination of both
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00