no classification
no tag
no datas
posted on 2023-05-03 19:31 read(970) comment(0) like(28) collect(4)
How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions?
Failing to use the global
keyword where appropriate often causes UnboundLocalError
. The precise rules for this are explained at UnboundLocalError on local variable when reassigned after first use. Generally, please close other questions as a duplicate of that question when an explanation is sought, and this question when someone simply needs to know the global
keyword.
You can use a global variable within other functions by declaring it as global
within each function that assigns a value to it:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
Since it's unclear whether globvar = 1
is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global
keyword.
See other answers if you want to share a global variable across modules.
Author:qs
link:http://www.pythonblackhole.com/blog/article/151/bd04255675b3b8ee313d/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!