首页 > 解决方案 > 如何使用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)

标签: pythonpython-3.xalgorithm

解决方案


根据您假设每个元素都是空格分隔的(不像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)

推荐阅读