[英]Python User-Defined Global Variables Across Modules: Issues calling them when other modules are run
我對Python相當陌生,目前正在學習在python程序中使用函數和多個模塊。
我有兩個模塊“ Functions_Practice_Main”(運行菜單)和“ Functions_Practice”,其中包含一個簡單程序的代碼,該程序可以計算出用戶的輸入是否除以7(我知道...相當愚蠢的做法)。
我想做的是讓用戶在運行菜單模塊時輸入其名稱,然后通過顯示整個程序來獲取此全局變量,以使程序更具個性。
但是,當我運行菜單模塊時,它會要求輸入兩次名稱。 輸入的名字顯示在“ 7分頻”程序中,輸入的名字顯示在菜單中。 我知道為什么會發生這種情況(由於導入了Functions_Practice模塊,要求在其余代碼有機會運行之前先知道Functions_Practice_Main模塊中的全局變量是什么),但我確實需要知道如何解決此問題。
運行菜單模塊時,如何使用戶輸入名稱ONCE,然后通過顯示整個程序來獲取此全局變量,以使其對用戶更具個性。
功能_實踐_主要
import Functions_Practice, sys
name = input("What is your name? ")
def main():
while True:
print(name, "'s Menu")
print("*******************")
print("1. Can you divide by 7?")
print("2. Quit")
print("*******************")
selection = int(input("Your number selection please..."))
if selection == 1:
Functions_Practice.main()
elif selection == 2:
sys.exit()
else:
print("Your number selection was invalid, please try again...")
if __name__ == '__main__':
main()
* 函數實踐*
import Functions_Practice_Main
def inputData(name):
print(name)
number = int(input(" Please enter your number: "))
return number
def processData(number):
answer = number % 7
if answer == 0:
remainder = True
else:
remainder = False
return remainder
def outputData(remainder):
if remainder == True:
print("The number you entered doesn't have a remainder")
elif remainder == False:
print("The number you entered does have a remainder")
def main():
number = inputData(Functions_Practice_Main.name)
remainder = processData(number)
outputData(remainder)
if __name__ == '__main__':
main()
將模塊作為腳本運行並不算將其作為模塊導入。 當Functions_Practice_Main.py腳本導入Functions_Practice,而Functions_Practice導入Functions_Practice_Main時,Python不在乎Functions_Practice_Main.py中的代碼已作為主腳本運行。 Python將再次運行它以生成模塊。
您如何解決這個問題? 好吧,您應該做幾件事。 首先,盡可能避免循環進口。 而不是讓Functions_Practice導入Functions_Practice_Main,而是將來自Functions_Practice_Main的所有數據Functions_Practice需要作為函數參數。
在Functions_Practice_Main中:
Functions_Practice.interactive_remainder_test(name)
在Functions_Practice中:
def interactive_remainder_test(name):
number = inputData(name)
remainder = processData(number)
outputData(remainder)
其次,是這樣的:
name = input("What is your name? ")
屬於文件main
,因為它們在導入文件時不應運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.