深度阅读

python how to use global variables

作者
作者
2023年08月22日
更新时间
11.03 分钟
阅读时间
0
阅读量

To use global variables in Python, you need to first declare them outside any functions or classes using the global keyword. This tells Python that the variable should have global scope, which means it can be accessed and modified from anywhere in the program.

Here’s an example:

# Define a global variable
global_var = "Hello world!"

# Define a function that modifies the global variable
def modify_global():
    global global_var
    global_var = "Goodbye world!"

# Call the function to modify the global variable
modify_global()

# Print the new value of the global variable
print(global_var)

In this example, we define a global variable called global_var and a function called modify_global() that modifies the value of the global variable. To indicate that we want to modify the global variable within the function, we use the global keyword followed by the name of the global variable.

Finally, we call the function and then print the new value of the global variable. Note that the global keyword is not used when accessing a global variable, only when modifying it.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。