python之局部变量引用赋值前的结果


通过正则表达式,实现加减

 

  昨晚在做计算器的时候,被一个BUG搞懵比了。现在再看看,发现我好小白啊~~

 

 

 1 #8+5+65
 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赋值前的结果。

 

 

转发注明出处,谢谢。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM