Python Beginner Essentials Exercise 4---Develop a calculator program

Source: Internet
Author: User

Always have a friend to ask me, listening to my lecture feel can understand, I say the example of writing can also be made, but one to oneself want to copy but write their own time, found that there is no train of thought, do not know how to start. To this I can only say, or because of the practice of less, usually never write code, learn a bit of grammar to be able to get the complex function is not realistic, learning language is a progressive process, not after tens of thousands of lines of code baptism, it is difficult to become an excellent programmer, in order to help beginners find some good practice basic examples , I will soon organize some of my lectures to some of the Python practice program to share to everyone, want to learn Python students can follow the example to do, I am sure, put my list of practice procedures are finished, you can basically do a qualified Pythoner!


Interested students can join the technical Exchange Group to study together: 29215534



Do a list of the topics today: Develop a simple calculator

Functional Requirements :

    • after a similar formula such as 1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)), the user input must be Self-analysis inside the (), +,-, *,/symbols and formulas, the result of the operation, the results must be consistent with the results of the actual calculator.

    • Implement subtraction

    • Meet priority levels


The required knowledge points:

    1. Process Control

    2. Function

    3. function recursion

    4. Regular expressions

    5. Operations for a list of common data types





Examples of answers:

Students please be sure to do their own first, do not look at my code below, I suppress or really suppress the time to compare.


Code logic:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/70/E4/wKioL1XAqR7hqRcKAAC8EP9u6Vo598.jpg "title=" Calculator logic. jpg "alt=" wkiol1xaqr7hqrckaac8ep9u6vo598.jpg "/>


Detailed code:

#_ *_coding:utf-8_*___author__ =  ' Jieli ' Import reimport sysdef remove_space (data_list) :     ' Remove the space element from the list ' '     for i in data_list:         if type (i)  is not int:             if len (I.strip ())  == 0:                 data_list.remove (i)      return  data_listdef fetch_data_from_bracket (Data_list,first_right_bracket_pos):      "takes the data from each pair of parentheses in a recursive form and evaluates the result ' '     print  ' data list: ', Data_ List    left_bracket_pos,right_bracket_pos = data_list.index (' ('), Data_ List.index (') ')  +1    print  ' \033[31;1mleft bracket pos:%s right_ bracket_pos: %s\033[0m ' &NBsp;% ( Left_bracket_pos,first_right_bracket_pos)     data_after_strip = data_list[left_ Bracket_pos:right_bracket_pos]    if data_after_strip.count ("(")  > 1:         print  ' fetch_data_from_bracket:%s \033[31;1m%s\033[ 0m left pos:%s '   % (data_after_strip,data_after_strip[1:] , left_bracket_pos)          #return  fetch_data_from_bracket (Data_after_strip[left_ Bracket_pos+1:],first_right_bracket_pos)         return fetch_data _from_bracket (Data_after_strip[1:],first_right_bracket_pos)     else:         print  ' Last: ', Len (Data_after_strip),data_after_strip         bracket_start_pos = first_right_bracket_pos - len (Data_after _strip)  +1  #  (takes two position        calc_res =  Parse_operator (Data_after_strip)         return calc_res,  bracket_start_pos,first_right_bracket_pos +1 # ')  takes one position ' Def parse_ Bracket (Formula):   #解析空格中的公式      "' Parse the formula in the space and calculate the result '      Pattern = r "\ (. +\)"     m = re.search (pattern,formula)   #匹配出所有的括号   ' 3 / 1      - 2 *  (  (60-30 *  (4-2) )  - 4*3/  (6-3*2)  ) '   after match is ' (  (60-30 *  (4-2))  - 4*3/  ( 6-3*2)   '     if m:        data_with_ Brackets = m.group ()          #print  list (data_with_ Brackets)     &NBsp;   data_with_brackets = remove_space (List (data_with_brackets))           #print  data_with_brackets         Calc_res = fetch_data_from_bracket (Data_with_brackets,data_with_brackets.index (')))          print  ' \033[32;1mresult:\033[0m ', calc_res         print calc_res[1],calc_res[2]         print  data_with_brackets[calc_res[1]:calc_res[2]]         del data_with_brackets[calc_res[1]:calc_res[2]]        data _with_brackets.insert (Calc_res[1], str (calc_res[0))   #replace  formula string with  caculation result 4        return parse_bracket (' '. Join (data_with_brackets))   #继续处理其它的括号     else:  #no  bracket in formula anymore         print  ' \033[42;1mcaculation result:\033[0m '  ,formuladef  caculate_1 (Formula): # for multiplication and division     Result = int (formula[0])   # e.g [' 4 ',  '/',  ' 2 ',  ' * ',  ' 5 '],  loop start from  '/'     last_operator = None     formula = list (Formula)     nagative_mark = False     for index,i in enumerate (formula[1:]):         if i.isdigit ():             if  nagative_mark:                 i = int ('-' +i) &NBSp;               nagative_mark  = False            else:                 i = int (i)               #print   ' +++> ', result,last_operator,i             if last_operator ==  ' * ' :                result   *= i            elif last_operator  ==  '/':                 try:                     result /= i                 except ZeroDivisionError,e:                     print  "\033[31;1merror:%s\033[0m"  % e                      sys.exit ()         elif i ==  '-':             nagative_mark = True         else:             last_operator = i    print  ' multiplication operation results: '  , result     return resultdef caculate_2 (data_list,operator_list):     "eg.  data_list:[' 4 ',  3, 1372,  ' 1 ']  operator_list:['-',  ' + ',  '-'     data_list =  remove_space (data_list)     print  ' caculater_2: ',data_list,operator_list     result = int (data_list[0])     for i in data_ list[1:]:        if operator_list[0] ==  ' + ':             result += int (i)          elif operator_list[0] ==  '-':             result -= int (i)          del operator_list[0]    print  ' Caculate_2 result: ', result     return  resultdef parse_operator (Formula):    print  ' Start Operation formula: ', formula    formula = formula[1:-1]  #remove  bracket    low_priorities  = re.findall (' [+,-] ', '. Join (Formula))     data_after_removed_low_priorities  = re.split (' [+,-] ',  '. Join (Formula))     print  ' Remove the formula list after the addition and subtraction, first count multiplication: ', Data_after_removed_low_priorities    for index,i in enumerate (Data_after_ removed_low_priorities):         if i.endswith ("*")  or  I.endswith ("/")  :            data_after_ removed_low_priorities[index] +=  '-'  + data_after_removed_low_priorities[index+1]             del data_after_removed_low_priorities[ index+1]    print  '---------->handle nagative num: ', data_after_removed_ low_priorities     #计算乘除运算     nagative_mark = false    for index,i  in enumerate (data_after_removed_low_priorities):         if  not i.isdigit ():             if len (I.strip ())  == 0:                 nagative_mark = True             else: #remove  space                 string_to_list = []                 if nagative_mark:                     prior_l =  '-'  +  i[0]  #                     nagative_mark = False                 else:                     prior_l = i[0]                 for l in i[1:] :                     if  L.isdigit ():                         if prior_l.isdigit ()  or len (prior_l)  >1 : # two letter should be combined                             prior_l + = l                         else:                              prior_l = l                     else: # an operator * or /                          string_to_list.append (prior_l)                          string_to_list.append (L)                          prior_l = l   #reset  prior_l                 else:                     string_to_list.append (prior_l)                  print  '---;: : ', string_to_list                 calc_res = caculate_1 (string_to_list)   #乘除运算结果                  data_after_removed_low_priorities[index] =  calc_res                 #print   '--->string  To list: ',string_to_list                  #print   ' +> ', Index, re.split (' [*,/] ', i)                   ' Operators = re.findall (' [*,/] ', i)                 data =  re.split (' [*,/] ', i)                  combine_to_one_list = map (none,data,operators)                  combine_to_one_list =re.split ("[\[,\],\ (,)," ', None] ",  str (combine_to_one_list))                  combine_to_one_list =  ". Join (Combine_to_one_list). Split ()                  print  '-',combine_to_one_list                  #print  operators,data ' '              #caculate_1 (combine_to_one_list)          else :             if nagative_mark:                 data_after_removed_low_priorities[index] =  '-'  + i     print  ' start operation plus minus after removing *  and  /: ',  data_after_removed_low_priorities,low_ priorities     #计算加减运算     return caculate_2 (data_after_removed_low _priorities,low_priorities)      #print  formuladef main ():     While true:   &nbsP;    user_input = raw_input (">>>:"). Strip ()          if len (user_input)  == 0:continue          #parse_bracket (user_input)         user_input =  ' ('  + user_input +  ') '          #parse_bracket ('  1 - 2 *  (  (60-30 + ( -40/5)  *  (9-2*5/3 + 7 /3*99/4* 2998 +10 * 568/14 )  -  ( -4*3)/  (16-3*2)  )   ')          parse_bracket (user_input)         print   ' \033[43;1mpython calculator results: \033[0m ', eval (user_input) if __name__ ==  ' __main__ ':     main ()


This article is from the "alex3714" blog, make sure to keep this source http://3060674.blog.51cto.com/3050674/1681693

Python Beginner Essentials Exercise 4---Develop a calculator program

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.