Implement a simple calculator with Python

Source: Internet
Author: User
Write your own calculator one, function analysis

The user enters a similar expression like this (4+ 50)-((100 + 40) *5/2-3*2* 2/4+9) * ((((3 + 4)-4)-4), assuming that the expression contains no special symbols except spaces, ' + ', '-', ' * ', '/', and parentheses, and then straight Then write the code to parse the expression, achieve subtraction , The final result and the actual computer calculated results must be consistent.

Second, the required knowledge points
  • Processing of strings
  • The use of regular expressions
  • function recursion
Three, the procedure realization process analysis
  1. Processing user-entered strings, removing extra spaces
  2. Processing strings with regular expressions, extracting numbers and operators from them, and converting them into lists
  3. Write a function that handles the basic expression of basic operations without parentheses
  4. Write a function that recursively handles parentheses, computes the expression in the inner parenthesis, and then replaces the inner parentheses with the computed result, at the end of the recursive outer layer, and returns the desired result.
Iv. Concrete implementation Process 1. Handling user Input

Processing user input is simple, here we just need to remove the extra space, the implementation code is as follows:

  

Implement a simple calculator with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.