Reputation: 13
I have written a basic program to do arithmetic operations, where the user input will be in a single line containing two integers and operator(+, -, *, /, and %) similar to 3 + 5
.
I have written this code so far it works for all positive integers but when I try to give a negative integer it throws IndexError
def calculator(given_input):
cal = []
def operation(given_input):
int_input = given_input.split()
for i in int_input:
if i.isdigit():
cal.append(int(i))
#for addition
if ("+" in given_input):
operation(given_input)
print(cal[0] + cal[1])
#for subraction
if ("-" in given_input):
operation(given_input)
print(cal[0] - cal[1])
#for division
if ("/" in given_input):
operation(given_input)
print(cal[0] - cal[1])
#for multiplication
if ("*" in given_input):
operation(given_input)
print(cal[0] * cal[1])
#for modulous
if ("%" in given_input):
operation(given_input)
print(cal[0] % cal[1])
given_input = input()
calculator(given_input)
Upvotes: 0
Views: 377
Reputation: 54148
From the supposition you make that each element is space-separated, (not like 3+4
) as you used given_input.split()
that splits on space, you can directly use the index of that element. Also don't call operation
in each branch, call it before or better just execute the code directly
def calculator(given_input):
cal = []
int_input = given_input.split()
cal.append(int(int_input[0]))
cal.append(int(int_input[2]))
if "+" == int_input[1]:
print(cal[0] + cal[1])
elif "-" == int_input[1]:
print(cal[0] - cal[1])
elif "/" == int_input[1]:
print(cal[0] - cal[1])
elif "*" == int_input[1]:
print(cal[0] * cal[1])
elif "%" == int_input[1]:
print(cal[0] % cal[1])
To handle multiple situations, with spaced or non-spaced content, use a regular expression with re
module, a regex like (-?\d+)\s*([+-/*%])\s*(-?\d+)
(-?\d+)
a possible minus, then an amount of digit\s*
a posible amount of spaces([+-/*%])
any char in these 5 +-/*%
\s*
a posible amount of spaces(-?\d+)
a possible minus, then an amount of digitimport re
def calculator(given_input):
int_input = re.search("(-?\d+)\s*([+-/*%])\s*(-?\d+)", given_input)
if not int_input:
print("Format error of '", int_input, "'")
return
a, operator, b = int_input.groups()
a, b = int(a), int(b)
if "+" == operator:
print(a + b)
elif "-" == operator:
print(a - b)
elif "/" == operator:
print(a / b)
elif "*" == operator:
print(a * b)
elif "%" == operator:
print(a % b)
Upvotes: 2