我创建了2个不同的python文件。 名为“game.py”的第一个文件的代码为:
h = int(input("Pick number 1 or 2: "))
def game():
if h == 1:
print ("You lose!")
if h == 2:
print ("You win!")
def play_again():
rounds = input("Play again? (Y/N): ")
if rounds == "Y":
game()
if rounds == "NO":
print ("Game Over")
如图所示,我在这个文件中有2个函数。
然后我用我的main函数创建了另一个文件,调用这两个函数。以下是其中的代码:
import game
def main():
game.game()
game.play_again()
main()
当我在控制台上运行时,会打印“选择号码1或2:”。但是,如果我再次运行它,它会打印“再次播放?(Y / N):”。
我如何解决这个问题,以便每当我运行代码时它只打印“选择号码1或2:”?
答案 0 :(得分:0)
maingame.py:
import game
game.game()
if __name__ == "__main__":
print("maingame.py is being run directly")
else:
print("maingame.py is being imported into another module")
game.py:
def game():
h = input("Pick number 1 or 2:\n")
if h == 1:
print("You lose!")
if h == 2:
print("You win!")
play_again()
def play_again():
rounds = raw_input("Play again? (Y/N): ") # just use input() for python3
if rounds == 'Y':
game()
if rounds == 'N':
print("Game Over")
另请参阅:What does if __name__ == "__main__": do?
和:Python 2.7 getting user input and manipulating as string without quotations
您可以从maingame.py中删除三个底线,但应该阅读相关链接,以了解if __name__ == "__main__":
的作用和原因。通常你会写:
if __name__ == "__main__":
main()
从命令行调用时,这将确保您的文件将以main()开头运行。