python变量使用前必须赋值_python之局部变量引用赋值前的结果

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

昨晚在做计算器的时候,被一个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赋值前的结果。

转发注明出处,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值