Python中的加法出错

Python中的加法出错,python,Python,我是python的初学者,正在编写一个基本的计算器 while True: print("PyCalc") print() print() init=input("Press 1 for Basic arithmetic") if init=="1": input1=input("Basic Arithmetic...Only +,-,*,/ accepted...") input2=re.findall(r'\d+|\+|

我是python的初学者,正在编写一个基本的计算器

while True:
    print("PyCalc")
    print()
    print()
    init=input("Press 1 for Basic arithmetic")
    if init=="1":
        input1=input("Basic Arithmetic...Only +,-,*,/ accepted...")
        input2=re.findall(r'\d+|\+|\-|\*|\/',input1 )
        ans =basiccalc(input2)
        print(ans )
方法basiccalc:

def basiccalc(givenlist):
    ans=int(givenlist[0])
    for pt in givenlist:
        if str(pt).isdigit():
            continue
        elif pt=='+':
            pos=givenlist.index(pt)
            ans=ans+int(givenlist[pos+1])

return ans
当我运行程序时…添加2个数字可以正常工作

  PyCalc


  Press 1 for Basic arithmetic1
  Basic Arithmetic...Only +,-,*,/ accepted...2+3
  5
但当我输入两个以上的数字…它会给我一个错误的答案

PyCalc


Press 1 for Basic arithmetic1
Basic Arithmetic...Only +,-,*,/ accepted...2+4+5+6
14

为什么我会得到这样的答案?

第一个问题,您必须使用原始输入函数而不是输入,因为输入已经对输入进行了算术运算

第二个问题是basiccalc函数中有两个以上的数字,最后一个没有计算,请尝试:

import re

def sum(a,b):
    return a+b


def basiccalc(givenlist):
    ans=0
    op=sum
    for pt in givenlist:
        if str(pt).isdigit():
            ans = op(ans,int(pt))
            last = int(pt)
        elif pt=='+':
            op=sum
    return ans            

input1=raw_input("Basic Arithmetic...Only +,-,*,/ accepted...")
input2 = re.findall( r'\d+|\+|\-|\*|\/', input1 )
ans = basiccalc(input2)
print(ans)
有关解析的更多信息,请查看龙书代码示例:

提示:2+4+5+6。index+将只返回1。