SyntaxError:在全局声明之前使用了名称“variable”

2024-09-29 20:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里写这个脚本:

http://www.codeskulptor.org/#user40_OuVcoJ2Dj1_8.py

我的错就在于这条准则:

if 'i' not in globals():
    global i
    if 'j' in globals():
        i = j
    else:
        i = 0

如果j存在于全局范围内,我想将i分配给j。如果j不存在,i从0开始。如果输入正确,j可能在稍后的脚本中得到全局声明。在

按左上角的play运行脚本。在


Tags: inpyorg脚本httpifwwwnot
2条回答

这不是Python中全局变量的工作方式。如果我猜对了你的意图,你需要这个代码:

if 'i' not in globals():
    global i

要解释类似“如果当前没有一个名为i的全局变量,那么用这个名称创建一个全局变量。”这不是该代码所说的(正如所写,它没有意义)。该代码最接近的翻译如下:

如果没有名为i的全局变量,那么当我试图在此范围内使用变量i时,我引用的是全局{}(它不存在),而不是创建一个只存在于当前范围内的新变量i。在

global从不创建任何东西,它只告诉解释器在哪里查找您所指的内容。在

一些可能有用的链接:

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

https://infohost.nmt.edu/tcc/help/pubs/python/web/global-statement.html

可以在不设置全局参数的情况下声明它们,并且它们不会显示在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()

^{pr2}$

这将返回:

test is not in globals

test is now 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

相关问题 更多 >

    热门问题