我在这里写这个脚本:
http://www.codeskulptor.org/#user40_OuVcoJ2Dj1_8.py
我的错误在于此代码:
if 'i' not in globals():
global i
if 'j' in globals():
i = j
else:
i = 0
如果i
存在于全局范围内,我想将j
分配给j
。如果j
不存在i
从0开始,如果输入正确,则j
可能会在脚本中稍后全局声明。
您可以通过按左上角的播放来运行脚本。
答案 0 :(得分:2)
这不是全局变量在Python中的工作方式。如果我正确地猜测你的意图,你需要这个代码:
if 'i' not in globals():
global i
被解释为“如果当前没有名为i
的全局变量,则创建一个具有该名称的全局变量。”这不是那段代码所说的(而且正如所写,它没有意义)。该代码的最接近的翻译类似于:
如果没有名为i
的全局变量,当我尝试在此范围内使用变量i
时,我指的是全局i
(不存在)而不是创建仅存在于当前范围内的新变量i
。
global
从不创建任何内容,它只会告诉解释器在哪里查找您所指的内容。
一些可能有用的链接:
https://infohost.nmt.edu/tcc/help/pubs/python/web/global-statement.html
答案 1 :(得分:0)
可以在不设置全局变量的情况下声明全局变量,并且它们不会在globals()
调用中显示。例如,在你的程序结束时,你可以声明所有的全局变量,但是在你想要之前不要设置它们。
global test
if 'test' in globals():
print("test is in globals")
else:
print ("test is not in globals")
这将导致test is not in globals
但是,如果您在执行此操作后将值设置为test
,则它将位于globals()
global test
if 'test' in globals():
print("test is in globals")
print(test)
else:
print ("test is not in globals")
test=45
if 'test' in globals():
print("test is now in globals")
print(test)
else:
print ("test is still not in globals")
这将返回:
测试不在全局
中测试现在是全局
45
意味着您可以声明变量的名称,以查看它是否在globals()
中,然后进行设置并再次检查。在您的代码中,您可以尝试:
global i
global j
if 'i' not in globals():
if 'j' in globals():
i = j
else:
i = 0
if 'j' not in globals():
j = something
else:
j =somethingElse