Home > Backend Development > Python Tutorial > How to define global variables in python

How to define global variables in python

PHPz
Release: 2024-03-01 17:04:22
forward
856 people have browsed it

How to define global variables in python

In python, global variables can be defined anywhere outside the function. When using global variables inside a function, you need to use the global keyword to declare the variable as a global variable. Here is an example:

# 定义全局变量
global_var = 10

def my_function():
# 使用全局变量
print(global_var)

def another_function():
# 修改全局变量
global global_var
global_var = 20

# 调用函数
my_function() # 输出:10
another_function()
my_function() # 输出:20
Copy after login

In the above example, global_var is a global variable, which is used and modified in the my_function() function. In the another_function() function, the global keyword is used to declare global_var as a global variable, and then its value is modified. Finally, call the my_function() function again, and you can see that the value of the global variable has been modified to 20.

The above is the detailed content of How to define global variables in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:lsjlt.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template