[英]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.