我从另一个python文件导入了一个函数,它使我的代码运行了2次。
代码是这样的
n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)
经过几行之后:
from Partie_C import boucle_jeu
并且此导入使该代码再次运行:
n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)
所以您了解...如果没有它,它只会询问“ n”打印消息并完成(仅一次)
您所描述的唯一合理的方式可能是,如果Partie_C
正在导入包含n = ...
的文件,从而导致循环导入。
循环导入将使代码运行两次,因为导入将导致解释导入的文件。如果导入Partie_C
,它将运行。如果Partie_C
然后导入此代码,则此代码将作为导入的结果运行。
# Code runs here obviously
n = int(input("\nCombien des disques? \nNombres des disques: "))
display = init(n)
print("\nYour playground looks like this: \n", display)
# Indirectly imports this file, causing the whole file to be interpreted again, running the above code again
from Partie_C import boucle_jeu
要解决此问题,请将代码放在函数中而不是放在顶层,或使用导入保护(if __name__ == "__main__"
)。或者更好的是,没有循环进口。圆形进口通常被认为是一种代码气味。重新排列代码,以免彼此导入两个文件。