我正在尝试编写一个评估算术表达式的“简单”Python计算器。表达式作为一个字符串(一个程序参数)给出,由操作符(正整数)组成,由运算符(+和 - )分隔。程序评估表达式并打印出结果。如果提供的参数太多或太少,或者单个程序参数格式错误,程序将打印“ERROR”(不带引号)。一些例子:
python calc.py 09-100-50
-141
python calc.py ""
ERROR
python calc.py 0+45+50-800+-5
ERROR -> gives error because there's a +- combination
python calc.py -1
ERROR
python calc.py 1
1
事情是:我有我的代码,但它没有添加或减去数字,我怎么能检查是否有+ - 组合
import sys
t = len(sys.argv)
num = ""
new_num = 0
if(t > 2 or t == 1):
print("ERROR")
exit()
s = sys.argv[1]
new_num_f = 0
if(sys.argv[1] == ""):
print("ERROR")
exit()
if(s[0] == "-"):
print("ERROR")
exit()
try:
for i in range(len(s)):
if(len(s) == 1):
new_num = s[0]
elif(str(s[i]) == "+"):
new_num += int(num)
num = ""
elif(s[i] == "-"):
new_num -= int(num)
num = ""
elif(str):
num += s[i]
new_num_f = new_num
except(SyntaxError): #this is a wrong error, I don't know what error to use
print("ERROR")
exit()
print(str(new_num_f))
如果有人能告诉我如何解决这个问题并解释为什么要使用它,非常感谢
答案 0 :(得分:0)
我制作的样式与给定的代码略有不同,但是效果很好。
from sys import argv
def calculate(expression_string):
expression_length = len(expression_string)
letter_index = 0
operands = []
operators = []
while letter_index < expression_length:
if expression_string[letter_index].isdigit():
operand = ""
while letter_index < expression_length and expression_string[letter_index].isdigit():
operand += expression_string[letter_index]
letter_index += 1
operands.append(int(operand))
else:
operators.append(expression_string[letter_index])
letter_index += 1
result = operands.pop(0)
while operators != []:
operator = operators.pop(0)
if operator == "+": result += operands.pop(0)
elif operator == "-": result -= operands.pop(0)
return result
def main():
if len(argv) == 1:
print("No expression is provided!")
return
if list(filter(lambda letter: not letter.isdigit() and letter not in [ "+", "-" ], argv[1])) != []:
print("Expression should cosist of digits & +, - signs only!")
return
operands = argv[1].replace("+", " ").replace("-", " ").split()
operators = list(filter(lambda letter: not letter.isdigit(), argv[1]))
if len(operands) - len(operators) != 1:
print("Expression is incorrect!")
return
result = calculate(argv[1])
print(result)
if __name__ == "__main__":
main()