python之局部变量引用赋值前的结果
生活随笔
收集整理的這篇文章主要介紹了
python之局部变量引用赋值前的结果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
通過正則表達式,實現加減
?
? 昨晚在做計算器的時候,被一個BUG搞懵比了。現在再看看,發現我好小白啊~~
?
?
1 #8+5+6-52 num = input("please input:")3 sa = re.split(r'(\D)', num) #區配到非數字則分割4 5 6 def func(s):7 #result = 08 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賦值前的結果。
?
?
轉發注明出處,謝謝。
?
轉載于:https://www.cnblogs.com/zhangyubao/p/6973824.html
總結
以上是生活随笔為你收集整理的python之局部变量引用赋值前的结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 疏通下水道多少钱啊?
- 下一篇: 【大话设计模式】——浅谈设计模式基础