Home >Backend Development >Python Tutorial >How to use global variables in a function in Python

How to use global variables in a function in Python

silencement
silencementOriginal
2019-05-24 14:51:2436644browse

How Python uses global variables in a function: This can be achieved through the global statement. The global statement can declare one or more variables as global variables. Multiple variables need to be separated by commas, but this declaration is only valid in the current code block.

How to use global variables in a function in Python

#When using python functions, we often encounter problems with parameter definitions. If you do not declare a global variable, an error

How to use global variables in a function in Python

will be reported, which means that count is a local variable and has not been assigned a value before using it. Global variables cannot be used directly within functions.

How to use global variables in a function in Python

# It can be seen that num in the function is a local variable. Is there any way to use global variables within the function? According to the official documentation, you can use the global statement:

The global statement can declare one or more variables as global variables. This declaration is only valid within the current block of code. Otherwise, there is no way to access global variables. So add a global statement in the function: multiple variables declared using global need to be separated by commas, as follows

How to use global variables in a function in Python

If you want to call global variables in a function, a global statement is required. After calling the global variable, the value of the global variable may also change accordingly, if it is redefined like count = count 1, otherwise the global variable is just called. You can also call the variable method through class to achieve the effect of global variables.

The role of global is equivalent to passing parameters. If you want to use a variable declared outside a function, use global to declare the variable. This is equivalent to passing the variable in. The variable can now be referenced.

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

Statement:
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