在Python中,可以使用global關鍵字來聲明全局變量,以便在函數內部修改全局變量的值。下面是一個示例:
global
x = 10 def my_func(): global x x = 20 my_func() print(x) # 輸出 20
在上面的示例中,通過在函數my_func()中使用global x聲明,將x變量標記為全局變量。然后,在函數內部對x進行賦值操作,修改了全局變量的值。最后,打印x的值為20。
my_func()
global x
x