Addition going wrong in Python -


I am starting in Python and writing the original calculator

  while correct: Print Init == "1": input1 = input ("Basic arithmetic ... only +, -, *, / has been accepted") ("PyCalc") print () init = input ("1 for basic arithmetic Press ") ...") input2 = re.findall (r '\ d + | \ + | \ | | * * | \ /', input1) ans = basiccalc (input2) print (ans)  < Basic pre-requisites:  
  DEF Basic CLC (given list): ans = int (given list [0]) in the given list PT A: If str (pt) .isdigit (): elif pt = = '+': Pos = given list.index (pt) ans = ans + int (given list [pos + 1]) return ans  < / Pre> 

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

PyCalc Press 1 original arithmetic for basic arithmetic ... only + , -, *, / Approved ... 2 + 3 5

But when I enter more than 2 numbers ... it gives me a wrong answer Basic arithmetic: PyCalc Press 1 for basic arithmetic 1 ... Only +, -, *, / Approved .. .2 + 4 + 5 + 6 14

Why do I get such a reply? First of all, you should use the raw_input function instead of input, because the input is already counted arithmetic action. On input.

The second problem is for more than 2 numbers in your basic calculator function, which was not calculated at the last time, try that:

  import def def Amount (A, B): AR BEF Basic CLC (given list): Return to answer = 0 op = sum for PT in the given list: if str (pt) .isdigit (): ans = op (ans, Int (pt)) last = int (pt) Elif pt == '+': op = sum return answer input1 = raw_input ("basic arithmetic ... only +, -, *, / allowed ...") input2 = Re.findall (r '\ d + | \ + | \ | \ | | * | \ /', input1) ans = basiccalc (input2) print (ans)   

For more information on parsing the Dragon Book Code example:

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -