Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python函数如何看到外部变量?_Python_Python 3.x - Fatal编程技术网

python函数如何看到外部变量?

python函数如何看到外部变量?,python,python-3.x,Python,Python 3.x,当我运行此python代码时,我得到: 一, 一, 函数test1如何知道x而不将其作为参数传递?在文件的主体中定义的变量称为全局变量 它将在整个文件中以及导入该文件的任何文件中可见 这里x是一个全局变量 请尝试下面的代码 def test1(): print(x) def test2(x): print(x) x=1 test1() test2(x) 这里将显示输出 def test1(): x=2 print(x) def test2(x): p

当我运行此python代码时,我得到:

一,

一,


函数test1如何知道x而不将其作为参数传递?

在文件的主体中定义的变量称为全局变量

它将在整个文件中以及导入该文件的任何文件中可见

这里
x
是一个全局变量

请尝试下面的代码

def test1():
   print(x)

def test2(x):
   print(x)

x=1
test1()
test2(x)
这里将显示输出

def test1():
    x=2
    print(x)


def test2(x):
   print(x)

x=1
test1()
test2(x)
因为test1将打印其局部变量
x

您可以使用
global
关键字修改
test1()中全局变量
x
的值

输出

def test1():
    global x
    x=2
    print(x)


def test2(x):
   print(x)

x=1
test1()
test2(x)

因为
x
是一个全局变量?变量在语句运行时解析,而不是在函数声明时解析。当您调用test1时,x存在于全局范围内,因此test1的代码可以看到它。请参阅官方文档:现在您已经了解了全局变量,请谨慎使用它们@沙哈尔感谢您的正确标记。你也能投一票吗:)
def test1():
    global x
    x=2
    print(x)


def test2(x):
   print(x)

x=1
test1()
test2(x)
2
2