Addition going wrong in Python
Question: I am a beginner at python and am writing a basic calculator

    
    
    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 )
    

The method 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
    

when I run the program...adding 2 numbers works correctly.

    
    
      PyCalc
    
    
      Press 1 for Basic arithmetic1
      Basic Arithmetic...Only +,-,*,/ accepted...2+3
      5
    

but when I enter more than 2 numbers...it gives me a wrong answer

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

why do I get such an answer?


Answer: First problem you must use raw_input function instead of input, because input
already compute arithmetique operation on input.

Second problem is in your basiccalc function for more than 2 number the last
one was not calculate, try that:

    
    
    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)
    

For more information about parsing look at Dragon Book code example :
<https://github.com/lu1s/dragon-book-source-
code/blob/master/parser/Parser.java>

