我对 Python 相当陌生,目前正在学习在 Python 程序中使用函数和多个模块。
我有两个模块“Functions_Practice_Main”(运行菜单)和“Functions_Practice”,其中包含一个简单程序的代码,该程序可以计算出用户的输入是否除以 7(我知道......非常无聊的练习)。
我想要做的是让用户在菜单模块运行时输入他们的名字,然后通过在程序中显示这个全局变量来使程序更加个性化。
但是,当我运行菜单模块时,它会要求输入两次名称。输入的第一个名字显示在“除以 7”程序中,输入的第二个名字显示在菜单中。我理解为什么会发生这种情况(由于 Functions_Practice 模块的导入要求在其余代码有机会运行之前知道 Functions_Practice_Main 模块中的全局变量是什么)但我真的需要知道如何解决这个问题。
如何让用户在菜单模块运行时输入他们的名字一次,然后通过显示整个程序来获取这个全局变量,以使其对用户更加个性化。
Functions_Practice_Main
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()
* Functions_Practice*
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()