[英]Global variables in multiples functions in Python
我将尝试通过示例来说明我的情况:
我使用全局声明变量,但仅在函数中有效,当我尝试另一个子函数不起作用时。
register.py
def main():
alprint = input("Enter something: ")
if alprint == "a":
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alCheck()
alTest()
main()
和content.py
from register import CheckTest
if CheckTest == "ad":
print("You are welcome!")
当我在main的一个子函数(函数,alTest())中声明此变量checkTest时,使用全局并导入到另一个文件中,它不起作用,我尝试了很多事情,但是什么也没做。
这是可行的 ,但如果用户输入以外的东西a
对第一input
, CheckTest
没有定义,所以它提供了一个ImportError
。 您可能想尝试这样的事情:
def main():
global CheckTest, CheckDot
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alprint = input("Enter something: ")
if alprint == "a":
alCheck()
alTest()
else:
CheckTest = None
CheckDot = None
main()
这样,始终定义CheckTest
和CheckDot
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.