python - 如何使用python3计算计算器问题的负数?
问题描述
我编写了一个基本程序来执行算术运算,其中用户输入将在一行中包含两个整数和运算符(+、-、*、/ 和 %),类似于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)
解决方案
根据您假设每个元素都是空格分隔的(不像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)
推荐阅读
- javascript - jQuery自动完成:按向上箭头键未定义的值
- html - HTML href 路径奇怪的行为
- python - 从 HTML 中的 Javascript 中提取变量
- momentjs - Momentjs 总是用 isAfter 返回 false
- jakarta-ee - Spring @Profile 的 EJB 对应物
- reactjs - react-navigation 用于将本机发送到错误的屏幕
- css - CSS网格,行高动态
- ibm-cloud - 在 Windows 10 上安装 IBM Cloud CLI 时遇到问题
- java - 注释 @DateTimeFormat 不适用于 Spring boot 和 Thymeleaf
- ios - Xcode Class AXAccessQueue 在两者中都实现了