0

我对 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()
4

1 回答 1

0

将模块作为脚本运行并不算作将其作为模块导入。当 Functions_Practice_Main.py 脚本导入 Functions_Practice 并且 Functions_Practice 导入 Functions_Practice_Main 时,Python 并不关心 Functions_Practice_Main.py 中的代码是否已经作为主脚本运行。Python 将再次运行它以生成模块。

你如何解决这个问题?嗯,有几件事你应该做。首先,尽可能避免循环导入。不要让 Functions_Practice 导入 Functions_Practice_Main,而是将 Functions_Practice 需要的任何数据从 Functions_Practice_Main 作为函数参数传递。

在 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,因为它们不应该在导入文件时运行。

于 2013-08-15T17:57:10.117 回答