def read_lines():
readFileName = "readfile.txt"
f = open(readFileName, 'r+')
contents = f.read()
... # and so on
read_lines()
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到一个错误:
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
Run Code Online (Sandbox Code Playgroud) 可能重复:
Python变量范围问题
Python手册将范围定义为:
范围定义块内名称的可见性.如果在块中定义了局部变量,则其范围包括该块.如果定义发生在功能块中,则作用域将扩展到定义块中包含的任何块,除非包含的块为名称引入了不同的绑定.
我有这个程序:
import random
def f():
a = "Is the scope static?"
if random.randint(0, 1) == 1:
del a
print a
Run Code Online (Sandbox Code Playgroud)
打印失败的可能性为50%:
>>> f()
Is the scope static?
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in f
UnboundLocalError: local variable 'a' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我认为print语句有50%的可能性超出了'a'的范围,但我可能错了.Python中范围的"正确"解释是什么?Python中变量的范围是静态定义的吗?变量"a"的范围是什么?
我的问题是如何在python中初始化全局字符串变量例如,当我执行以下操作时.
24 def global_paths():
25 global RUN_PATH
26 global BASE_PATH
27 global EXE_SUFIX
28 global SPEC_PATH
29 global cmd_list
30
31 global RUN_PATH = "/run/run_base_ref_amd64-m64-gcc43-nn.0000/"
32 global BASE_PATH = "/SPECcpu2006/1.1/cdrom"
33 global EXE_SUFIX = "_base.amd64-m64-gcc43-nn"
34 global SPEC_PATH = BASE_PATH + "/benchspec/CPU2006/"
35 global cmd_list = {}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
global RUN_PATH = "/run/run_base_ref_amd64-m64-gcc43-nn.0000/"
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我在做什么错?
问题类似于此
我试图理解 Python 3 变量范围和nonlocal.
考虑以下函数(这只是一个示例):
def build_property(something):
def deco(func):
def getter(self):
return getattr(self, something)
def setter(self, value):
setattr(self, something, value)
return property(getter, setter)
return deco
Run Code Online (Sandbox Code Playgroud)
这在没有nonlocal. 但如果现在我想根据something我需要的非本地条件有条件地创建 getter 和 setter。
def build_property(something):
def deco(func):
nonlocal something # This is needed
if something.startswith('A'):
getter = None
else:
def getter(self):
return getattr(self, something)
if something.startswith('B'):
setter = None
else:
def setter(self, value):
setattr(self, something, value)
return property(getter, setter)
return deco
Run Code Online (Sandbox Code Playgroud)
为什么nonlocal在一种情况下需要,但在另一种情况下不需要?换句话说,为什么something如果在第一种情况下正确找到(没有nonlocal …
我已经开始自学python,并且注意到与全局变量和范围有关的某些奇怪事情。当我运行这个:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
Run Code Online (Sandbox Code Playgroud)
打印结果为23 ...但是,当我将返回值扩展为:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
Run Code Online (Sandbox Code Playgroud)
我在第6行收到以下错误:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么我在这里遇到错误,因为z是全局可访问的。
我无法理解我的Python代码中的问题.它给了我以下错误:
Traceback (most recent call last):
File "main.py", line 77, in <module>
main();
File "main.py", line 67, in main
count -= 1
UnboundLocalError: local variable 'count' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
这是代码的一部分
我定义了全局变量
count = 3
Run Code Online (Sandbox Code Playgroud)
然后我创建了方法main
def main():
f = open(filename, 'r')
if f != None:
for line in f:
#some code here
count -= 1
if count == 0:
break
Run Code Online (Sandbox Code Playgroud)
这可能有什么问题?
谢谢
我一直在尝试制作加密和解密系统,但我遇到了一个小错误.这是我的代码:
import sys
import pyperclip
def copy(data):
question = input("Copy to clipboard? ")
if question.lower() == 'yes' or question.lower() == 'y':
pyperclip.copy(data)
print("Encrypted message copied to clipboard.")
rerun()
elif question.lower() == 'no' or question.lower() == 'n':
rerun()
else:
print("You did not enter a valid input.")
copy(data)
def rerun():
ask = input("\nWould you like to run this program again? ")
if ask.lower() == "yes" or ask.lower() == "y":
print(" ")
run()
elif ask.lower() == 'no' or ask.lower() == 'n':
sys.exit("\nThank you!") …Run Code Online (Sandbox Code Playgroud) 我在一本关于语言描述的书中看到了这一点
On the other hand, a name can be bound to no object (a dangling pointer),
one object (the usual case), or several objects (a parameter name in a
recursive function).
Run Code Online (Sandbox Code Playgroud)
我们如何将名称绑定到多个对象?我们所谓的数组是不是所有元素具有相同的名称但具有索引?对于递归函数,如下例所示:
x = 0
def f(y):
global x
x += 1
if x < 4 :
y +=100
f(y)
else: return
f(100)
Run Code Online (Sandbox Code Playgroud)
名称是否y绑定了多个以递归方式创建的值,因为y名称表已经将名称绑定到初始值,并使用递归进行复制?
EDITED只需按下此处Visualizer并查看其生成的内容.:)
答案应该是2因为首先main()调用该函数,然后调用该first()函数,覆盖在任何函数之外定义的全局变量num = 0,从而将其变为具有全局范围的变量.但是我收到以下错误:
UnboundLocalError: local variable 'num' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
为什么我收到此错误?
def first():
num = num + 1
def main():
num = 1
first()
print(num)
num = 0
num_result = main()
print(num_result)
Run Code Online (Sandbox Code Playgroud) 我想在python3中按照以下几行做一些事情:
i = 1337
def g():
print(i)
i = 42
g()
Run Code Online (Sandbox Code Playgroud)
但得到以下错误
UnboundLocalError: local variable 'i' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我想我明白错误信息的含义,但为什么会这样呢?有没有办法绕过这个?
为什么 python3.8+ 在使用 := 时将结果视为嵌套 lambda 中的局部变量,但在其他情况下则不然?
>>> counter = (lambda result: (lambda: (result + 1)))(0)
>>> counter()
1
>>> counter = (lambda result: (lambda: (result := result + 1)))(0)
>>> counter()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
UnboundLocalError: local variable 'result' referenced before assignment
Run Code Online (Sandbox Code Playgroud) 我有以下功能:
def x():
print(min(0, 1))
min = 7
print(min)
Run Code Online (Sandbox Code Playgroud)
在它的面前(天真),它应打印0,然后7.实际上它引发了一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
UnboundLocalError: local variable 'min' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
定义min为局部变量如何min = 7防止它被用作手中的内置?Python是否__slots__在编译函数时构建局部变量列表(类似于类)?
python ×13
python-3.x ×5
binding ×1
encryption ×1
function ×1
global ×1
jes ×1
linux ×1
name-binding ×1
scope ×1
scoping ×1
string ×1