gpt4 book ai didi

python - 为什么我可以访问 Python 函数外部有条件定义的变量?

转载 作者:行者123 更新时间:2023-12-02 02:48:24 24 4
gpt4 key购买 nike

我有 C、C++ 和 Java 背景。所以我很好奇为什么下面的 Python 代码可以工作:

def f1():
print(xy)


if __name__ == "__main__":
print("Hello")
xy = 34
f1()

它打印:

Hello
34

如何访问函数f1中的xyxy 未在 f1 内部定义,xy 是在 if __name__ == "__main__" 的条件 block 中定义的>?

最佳答案

Global Variables

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

关于python - 为什么我可以访问 Python 函数外部有条件定义的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com