Or *_*imi 2 python variables runtime-error global-variables
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)
Run Code Online (Sandbox Code Playgroud)
我将计数器设置为全局变量,当我尝试运行此代码时,出现局部变量错误:
Traceback (most recent call last):
File "C:\Or\mypy\shift creator\shift cretor.py", line 144, in <module>
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
Run Code Online (Sandbox Code Playgroud)
我看到有人在这里问这个问题,他删除了他的 pyc 文件或其他东西(我不知道它是什么)并且它工作正常。为什么会出现这种情况呢?程序中的其他变量不会发生这种情况。
谢谢,或者
您需要声明一个全局变量
def shift_arrange(worker):
global counter
for day in days.values():
counter+=1
...
Run Code Online (Sandbox Code Playgroud)
由于您counter在该范围内进行修改,因此 python 将其视为局部变量,除非您将其声明为global. 如果您只需要阅读它,则没有必要。
考虑以下:
这有效:
c = 0
def f():
print c
f()
Run Code Online (Sandbox Code Playgroud)
虽然这不会:
c = 0
def f():
print c
c = 1
f()
Run Code Online (Sandbox Code Playgroud)
虽然这确实:
c = 0
def f():
global c
print c
c = 1
f()
print c # prints 1, f() modified the global value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5962 次 |
| 最近记录: |