通過正則表達式,實現加減
昨晚在做計算器的時候,被一個BUG搞懵比了。現在再看看,發現我好小白啊~~
1 #8+5+6-5 2 num = input("please input:") 3 sa = re.split(r'(\D)', num) #區配到非數字則分割 4 5 6 def func(s): 7 #result = 0 8 if s[1] == '+': 9 result = int(s[0]) + int(s[2]) 10 elif s[1] == '-': 11 result = int(s[0]) - int(s[2]) 12 13 for i in range(3): # 去掉前三個 14 s.remove(s[0]) 15 16 s.insert(0, result) #BUG:Local variable 'result' might be referenced before assignment more..局部變量引用賦值前的結果 17 print(s) 18 19 if len(s) == 1: 20 print(result) 21 else: 22 func(s) 23 24 func(sa)
注意第16行!!!
其實我昨晚運行的時候是有顯示有BUG的:
UnboundLocalError: local variable 'result' referenced before assignment
但是今天運行竟然沒有顯示錯誤了!邪了~
但是不管怎樣,pycharm 16行那里result都有下划線,提示:
Local variable 'result' might be referenced before assignment
怎么解決呢?
我早上又起來試試,在第7行加上result = 0,就可以了!
因為(我覺得)if/elif……里面都是一個范圍 ,有對result進行賦值,但在if/elif……外面是看不到的。
相當於局部變量s 引用了變量result賦值前的結果。
轉發注明出處,謝謝。