python中的赋值给i_本地变量在Python中赋值之前被引用,当我设置它的全局

from random import randint

shifts = [4, 4.2, 5, 6, 7]

days_names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']

workers_names = ['Itai', 'Or', 'Reut', 'Kuka', 'Aviel']

counter = 1

def shift_arrange(worker):

for day in days.values():

counter+=1

global avilable_shifts

avilable_shifts = check_avilable_shifts(day)

if not random_shifte_selector(worker,day): soft_reset(worker)

I set counter as a global variable, and when i try to run this code i get the local variable error:

Traceback (most recent call last):

File "C:\Or\mypy\shift creator\shift cretor.py", line 144, in

for w in workers.values(): shift_arrange(w)

File "C:\Or\mypy\shift creator\shift cretor.py", line 105, in shift_arrange

counter+=1

UnboundLocalError: local variable 'counter' referenced before assignmen

I saw some guy ask this question here, he deleted his pyc file or something(i don't know what is it) and its work fine. Why this is happen? Its not happen to other variables in the program.

Thanks, Or

解决方案

You need to declare a global variable

def shift_arrange(worker):

global counter

for day in days.values():

counter+=1

...

Since you modify counter in that scope, python treats it as a local variable, unless you declare it as global. If you only need to read it, that isn't necessary.

Consider the following:

This works:

c = 0

def f():

print c

f()

While this does not:

c = 0

def f():

print c

c = 1

f()

While this does:

c = 0

def f():

global c

print c

c = 1

f()

print c # prints 1, f() modified the global value

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值