我编写了一个基本程序来进行算术运算,其中用户输入将在一行中包含两个整数和类似于 3 + 5
的运算符(+、-、*、/ 和 %)。
到目前为止,我已经编写了这段代码,它适用于所有正整数,但是当我尝试给出一个负整数时,它会抛出 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)
答案 0 :(得分:2)
假设您将每个元素以空格分隔(不像 3+4
),因为您使用了在空间上分割的 given_input.split()
,因此您可以直接使用该元素的索引。也不要在每个分支都调用operation
,先调用或者直接执行代码最好
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])
要处理具有间隔或非间隔内容的多种情况,请使用带有 re
模块的正则表达式,如 (-?\d+)\s*([+-/*%])\s*(-?\d+)
之类的正则表达式
(-?\d+)
一个可能的减号,然后是一个数字\s*
可能的空格数([+-/*%])
这 5 个字符中的任意字符 +-/*%
\s*
可能的空格数(-?\d+)
一个可能的减号,然后是一个数字import 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)