廢話寫在前面:
本人小白初學Python,個人覺得自學編程有些知識點或是語法看的時候很明白,然鵝過了幾天不用就會忘,所以打算做點兒小項目來加深印象以便把知識點記牢。
如果只是無腦的照着別人的代碼敲,慢慢你會發現其實並沒有什么卵用,你只是把代碼敲上去了但是卻不懂別人為什么要這么寫。
自己如果一點兒都不動腦思考那是不行的,當一個具體的需求拿出來讓你去實現的時候,你就會發現一點兒思路也沒有。
自學最好是自己找個小需求來實現一下,在實現的過程中就會遇到很多問題,這個時候首先找出問題出現在哪里,然后一步一步調試解決問題,最后最后一定要記錄整理。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
簡單計算器開發需求:
實現簡單的加減乘除運算,以及帶括號的優先級解析,並能輸出正確的計算結果。
參考Alex大哥的:教學項目之-通過Python實現簡單的計算器
分析:
1.首先需要檢測用戶的輸入是否合法,如括號匹配問題
2.由於輸入的是字符串,所以需要進行字符串解析,解析出" + - * / ( ) "等符號
3.優先級解析,先計算括號里的內容,在計算乘除運算,最后算加減
1 #! -*- coding utf-8 -*- 2 #! @Time :$[DATE] $[TIME] 3 #! @Author :gg 4 5 import re 6 7 def comupute_mut_and_div(formula): 8 '''算乘除''' 9 operators = re.findall("[*/]", formula) 10 calc_list = re.split("[*/]", formula) 11 res = None # 細節賦值,第一遍for循環輪空 12 for index, i in enumerate(calc_list): 13 if res: # 第一次這里不執行,所以列表索引不會超出范圍 14 if operators[index-1] == "*": 15 res *= float(i) 16 elif operators[index-1] == "/": 17 res /= float(i) 18 else: 19 res = float(i) 20 print("\033[31;1m[%s]運算結果=\033[0m" % formula, res) 21 return res 22 23 def handle_special_sign(plus_and_sub_operators, mul_and_div): 24 """ 25 有時會遇到這種情況:1-2*-2/1 26 plus_and_sub_operators:['-', '-'] 27 mul_and_div:['1', '2*', '2/1'] 28 :param plus_and_sub_operators: 29 :param mul_and_div: 30 :return: 31 """ 32 for index, i in enumerate(mul_and_div): 33 i = i.strip() 34 if i.endswith("*") or i.endswith("/"): 35 mul_and_div[index] = mul_and_div[index] + plus_and_sub_operators[index] + mul_and_div[index+1] 36 del mul_and_div[index+1] 37 del plus_and_sub_operators[index] 38 return plus_and_sub_operators, mul_and_div 39 40 def handle_minus_inlist(operators_list, calc_list): 41 """ 42 處理加減帶負號的運算,1--4 = 1-(-4) = 1+4 43 operators_list: ['-'] 44 calc_list: ['1', '', '4.0'] 45 :param operators_list: 46 :param calc_list: 47 :return: 48 """ 49 for index, i in enumerate(calc_list): 50 if i == '': 51 calc_list[index+1] = "-" + calc_list[index+1] 52 del calc_list[index] 53 return operators_list, calc_list 54 55 def compute(formula): 56 ''' 57 解析字符串 58 :param formula: 輸入的為字符串 59 :return: 計算結果 60 ''' 61 formula = formula.strip("()") # 去括號,這里是(1+2-2*3+3/6) 62 plus_and_sub_operators = re.findall("[+-]", formula) 63 mul_and_div = re.split("[+-]", formula) # 取出乘除公式 64 65 plus_and_sub_operators, mul_and_div = handle_special_sign(plus_and_sub_operators, mul_and_div) 66 for i in mul_and_div: 67 if len(i) > 1: 68 print(i) 69 res = comupute_mut_and_div(i) 70 formula = formula.replace(i, str(res)) 71 else: 72 continue 73 calc_list = re.split("[+-]", formula) # 去除乘除公式 74 plus_and_sub_operators, calc_list = handle_minus_inlist(plus_and_sub_operators, calc_list) 75 total_res = None 76 for index, i in enumerate(calc_list): 77 if total_res: 78 if plus_and_sub_operators[index - 1] == "-": 79 total_res -= float(i) 80 elif plus_and_sub_operators[index - 1] == "+": 81 total_res += float(i) 82 else: 83 total_res = float(i) 84 print("\033[32;1m[%s]運算結果:\033[0m" % formula, total_res) 85 return total_res 86 87 def calc(formula): 88 '''去括號''' 89 brackets_flag = True 90 while brackets_flag: 91 m = re.search("\([^()]*\)", formula) 92 if m: 93 sub_res = compute(m.group()) # 替換 94 formula = formula.replace(m.group(), str(sub_res)) 95 else: 96 print("最終結果:", compute(formula)) 97 brackets_flag = False 98 99 if __name__ == '__main__': 100 # formula = "-1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" 101 formula = input("請輸入:") 102 calc(formula)
這里沒有實現輸入非法檢測,其他的都實現了,主要用的是正則表達式的提取、替換和分割,以及在for循環中使用enumerate函數。
后續再更新,完善其他更高級的運算以及圖形界面顯示。