How to set global variables in Python.

In Python, you can use the global keyword to define global variables.

Here is an example code for setting global variables:

# 在函数内部设置全局变量
def set_global_variable():
    global global_var
    global_var = "This is a global variable"

# 在函数外部访问全局变量
def access_global_variable():
    print(global_var)

# 调用函数
set_global_variable()
access_global_variable()

The output is:

This is a global variable

In the function set_global_variable(), the global keyword is used to declare global_var as a global variable. This allows direct access and use of the global_var variable in the function access_global_variable().

It is important to note that, before declaring a global variable using the global keyword inside a function, you cannot directly assign a value to the global variable, as it will be treated as a local variable.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds